0% found this document useful (0 votes)
2 views

8_Inheritance

The document discusses inheritance and interfaces in Java, highlighting the concept of superclass and subclass, and how subclasses inherit properties and methods from superclasses. It explains the use of the 'super' keyword for accessing superclass members and constructors, and covers method overriding and dynamic method dispatch. Additionally, it touches on the limitations of multiple inheritance in Java and the use of abstract classes for defining generalized forms.

Uploaded by

sindhus121985
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

8_Inheritance

The document discusses inheritance and interfaces in Java, highlighting the concept of superclass and subclass, and how subclasses inherit properties and methods from superclasses. It explains the use of the 'super' keyword for accessing superclass members and constructors, and covers method overriding and dynamic method dispatch. Additionally, it touches on the limitations of multiple inheritance in Java and the use of abstract classes for defining generalized forms.

Uploaded by

sindhus121985
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 57

Module 3

Inheritance and
Interfaces
Inheritance
2
 Inheritance is one of the cornerstones of object-oriented
programming because it allows the creation of hierarchical
classifications.
 Using inheritance, you can create a general class that defines traits
common to a set of related items. This class can then be inherited
by other, more specific classes, each adding those things that are
unique to it.
 In this a class that is inherited is called a superclass in the
terminology of Java,
 The class that does the inheriting is called a subclass. Therefore,
a subclass is a specialized version of a superclass. It inherits all of
the instance variables and methods defined by the superclass and
adds its own elements.
Inheritance Basics…. 3

• Java supports inheritance by allowing one class to incorporate


another class into its declaration.
• This is done by using the extends keyword. Thus, the subclass
adds to (extends) the superclass.

class subclassname extends superclassname


{
variable declaration;
methods declaration;
}
4
class A // Create a superclass class SimpleInheritance
{ {
5
public static void main(String args[])
int i, j;
{
void showij()
A superOb = new A();
{
B subOb = new B();
System.out.println("i and j: " + i + " " + j);
} superOb.i = 10;
} superOb.j = 20;
System.out.println("Contents of superOb: ");
// Create a subclass by extending class A.
superOb.showij();
class B extends A
{ subOb.i = 7;
subOb.j = 8;
int k;
subOb.k = 9;
void showk()
System.out.println("Contents of subOb: ");
{ subOb.showij();
System.out.println("k: " + k); subOb.showk();
} System.out.println();
void sum()
System.out.println("Sum of i, j and k in
{ subOb:");
System.out.println("i+j+k: " + (i+j+k)); subOb.sum();
} }
} }
/* In a class hierarchy, private members remain private to their class.
This program contains an error and will not compile. */
6
class A
{
int i; // public by default
private int j; // private to A

void setij(int x, int y)


{
i = x;
j = y;
}
}
// A's j is not accessible here.
class B extends A {
int total;
void sum() {
total = i + j; // ERROR, j is not accessible here
}
}
7
8
• Java does not support multiple and hybrid
inheritance with classes. 9
• In Java, we can achieve multiple inheritance only
through Interfaces.
Using super…. 10

• Sometimes we want to create a superclass that keeps the details


of its implementation to itself (data members will be kept
private).
• In this case there is no way for a subclass to directly access or
initialize these variables on its own.
• Since encapsulation is a primary attribute of OOP, it is not
surprising that Java provides a solution to this problem.
• Whenever a subclass needs to refer to its immediate superclass,
it can do so by use of the keyword super.
• super has two general forms.
1. The first calls the superclass constructor.
2. Used to access a member of the superclass that has been
hidden by a member of a subclass
11

• super is used to call the


• constructor
• methods
• and properties of parent class.
• the super keyword is used in the sub class
when you want to invoke a method from the
parent class when you have overridden it in the
subclass
Usage of java super Keyword
12

1. super() can be used to invoke immediate parent


class constructor
2. super can be used to refer immediate parent class
instance variable.
3. super can be used to invoke immediate parent
class method.
1.Using super to Call Superclass Constructors
13

• A subclass can call a constructor defined by its superclass by use


of the following form of super:

super(arg-list);

• Here, arg-list specifies any arguments needed by the constructor


in the superclass. super( )must always be the first statement
executed inside a subclass’ constructor.
14
Contd…
15
• To see how super( ) is used, consider this improved version of
the BoxWeight( ) class:

// BoxWeight now uses super to initialize its Box attributes.


class BoxWeight extends Box
{
double weight; // weight of box
// initialize width, height, and depth using super( )
BoxWeight(double w, double h, double d, double m)
{
super(w, h, d); // call superclass constructor
weight = m;
}
}
Contd…
 Here, BoxWeight( ) calls super( ) with the arguments w, h, and d. This 16 causes
the Box( ) constructor to be called, which initializes width, height, and depth
using these values.
 BoxWeight no longer initializes these values itself. It only needs to initialize the
value unique to it: weight. This leaves Box free to make these values private if
desired.
 In the preceding example, super( ) was called with three arguments.
 Since constructors can be overloaded, super( ) can be called using any form
defined by the superclass.
 The constructor executed will be the one that matches the arguments.
Pay special attention to this constructor in BoxWeight( ):
EXAMPLE
// construct clone of an object
BoxWeight(BoxWeight ob)
{ // pass object to constructor
super(ob);
weight = ob.weight;
Contd…
17
 Notice that super( ) is passed an object of type BoxWeight—not of type
Box. This still invokes the constructor Box(Box ob).
 As mentioned earlier, a superclass variable can be used to reference any
object derived from that class.
 Thus, we are able to pass a BoxWeight object to the Box constructor. Of
course, Box only has knowledge of its own members.
 Let’s review the key concepts behind super( ). When a subclass calls
super( ), it is calling the constructor of its immediate superclass.
 Thus, super( ) always refers to the superclass immediately above the
calling class. This is true even in a multileveled hierarchy.
2.A Second Use for super 18

 The second form of super acts somewhat like this, except that it
always refers to the superclass of the subclass in which it is used.
This usage has the following general form:
super.member;

 Here, member can be either a method or an instance variable.


 This second form of super is most applicable to situations in which
member names of a subclass hide members by the same name in the
superclass
19
Contd…
// Using super to overcome name hiding.
class A 20

{
int i;
}
// Create a subclass by extending class A.
class B extends A class UseSuper
{ {
int i; // this i hides the i in A public static void main(String args[ ])
B(int a, int b) {
{ B subOb = new B(1, 2);
super.i = a; // i in A subOb.show();
i = b; // i in B }
} }
void show()
{
System.out.println("i in superclass: " + super.i);
System.out.println("i in subclass: " + i);
}
}
21
class Room
{
int length, breadth; 22
Room(int x, int y)
{
length = x;
breadth = y;
}
int area()
{
return ( length * breadth );
}
}
class Hall extends Room Always the first statement to
{ be executed in the subclass
int height;
Hall(int x, int y, int z) constructor.
{
super(x, y);
height = z;
}
int volume()
{
return (length * breadth * height);
}
}
class InherTest
{ 23

public static void main(String args[])


{
Hall room1 = new Hall(14,12,10);
int area1 = room1.area();
int volume1 = room1.volume();
System.out.println("Area1 ="+area1);
System.out.println("Volume1 = "+volume1);

}
}
class A
{ 24
int i;
}

class B extends A
{
int i; // this i hides the i declared in A
B(int a, int b)
{
super.i = a; // i in A
i = b; // i in B
}
void show()
{
System.out.println("i in superclass: " + super.i);
System.out.println("i in subclass: " + i);
}
}
class UseSuper
25
{
public static void main(String args[])
{
B subOb = new B(1, 2);
subOb.show();
}
}
Creating a Multilevel Hierarchy….. 26

• Until now we have been using simple class hierarchies that


consist of only a superclass and a subclass.
• We can build hierarchies that contain as many layers of inheritance
as we like.
• For example, given three classes called A, B, and C, C can be a
subclass of B, which is a subclass of A.
• When this type of situation occurs, each subclass inherits all of
the traits found in all of its superclasses. In this case, C inherits all
aspects of B and A.
class A
{
int i; 27
void showi()
{
System.out.println("i : " + i );
}
}
// Create a subclass by extending class A.
class B extends A
{
int j;
void showj()
{
System.out.println(“j: " + j);
}
}
class C extends B
{
int k;
28
void showk()
{
System.out.println(“k: " + k);
}
void sum()
{
System.out.println("i+j+k: " + (i+j+k));
}
}

class MultiLevel
{
public static void main(String args[])
{
C obj = new C();
obj.i=1;
obj.j=2;
obj.k=3;
obj.sum();
}
}
When Are Constructors Called….. 29

• When a class hierarchy is created, in what order are the constructors


for the class that make up the hierarchy called?
• For example, given a subclass called B and a superclass called A, is
A's constructor called before B's or vice versa?
• The answer is, in a class hierarchy, constructors are called in the
order of derivation, from superclass to subclass.
// Demonstrate when constructors are called.
// Create a super class.
class A { 30
A() {
System.out.println("Inside A's constructor.");
}
}
class B extends A {// Create a subclass by extending class A.
B() {
System.out.println("Inside B's constructor.");
}
}
class C extends B { // Create another subclass by extending B.
C() {
System.out.println("Inside C's constructor.");
}
}
class CallingCons {
public static void main(String args[]) {
C c = new C();
}
}
Method Overriding…..
31
• In a class hierarchy, when a method in a subclass has the same
name and type signature as a method in its superclass, then the
method in the subclass is said to override the method in the
superclass.
• When an overridden method is called from within a subclass, it
will always refer to the version of that method defined by the
subclass.
• The version of the method defined by the super class will be
hidden.
32
33
class B extends A
// Method overriding. { 34
class A int k;
{
int i, j; B(int a, int b, int c)
{
A(int a, int b) super(a, b);
{ k = c;
i = a; }
j = b;
} // display k this overrides show() in
void show() A
{ void show()
System.out.println("i and j: " + i + " " + j); {
} System.out.println("k: " + k);
} }
}
class Override
35
{
public static void main(String args[])
{
B subOb = new B(1, 2, 3);
subOb.show(); // this calls show() in B
}
}
// For accessing the superclass method.
class B extends A { 36

int k;

B(int a, int b, int c) {


super(a, b);
k = c;
}

void show() {
super.show(); // this calls A's show()
System.out.println("k: " + k);
}
}
class Override
{ 37

public static void main(String args[])


{
B subOb = new B(1, 2, 3);
subOb.show(); // this calls show() in B
}
}

• Method overriding occurs only when the return types and


signatures of the two methods are identical.
• If they are not, then the two methods are simply overloaded.
Dynamic Method Dispatch
38
• Method overriding forms the basis for one of Java’s most powerful
concepts: dynamic method dispatch.
• Dynamic method dispatch is the mechanism by which a call to an
overridden method is resolved at run time, rather than compile
time.
• Java implements run-time polymorphism using dynamic method
dispatch.
• Let’s begin by restating an important principle: a superclass reference
variable can refer to a subclass object.
• Java uses this fact to resolve calls to overridden methods at run time.
BUT How.
• When an overridden method is called through a superclass
reference, Java determines which version of that method to execute
based upon the type of the object being referred to at the time the
call occurs.
Contd…
39
• Thus, this determination is made at run time. When different types
of objects are referred to, different versions of an overridden
method will be called.
• it is the type of the object being referred to (not the type of the
reference variable) that determines which version of an overridden
method will be executed.
• Therefore, if a superclass contains a method that is overridden by
a subclass, then when different types of objects are referred to
through a superclass reference variable, different versions of the
method are executed.
// Dynamic Method Dispatch
class A {
40
void callme() {
System.out.println("Inside A's callme method");
}
}
class B extends A {
// override callme()
void callme() {
System.out.println("Inside B's callme method");
}
}
class C extends A {
// override callme()
void callme() {
System.out.println("Inside C's callme method");
}
}
class Dispatch {
41
public static void main(String args[]) {
A a = new A(); // object of type A
B b = new B(); // object of type B
C c = new C(); // object of type C
A r; // obtain a reference of type A
r = a; // r refers to an A object
r.callme(); // calls A's version of callme
r = b; // r refers to a B object
r.callme(); // calls B's version of callme
r = c; // r refers to a C object
r.callme(); // calls C's version of callme
}
}
Using Abstract Classes
42
• There are situations to define a superclass that declares the
structure of a given abstraction without providing a complete
implementation of every method.
• That is, sometimes you will want to create a superclass that only
defines a generalized form that will be shared by all of its
subclasses, leaving it to each subclass to fill in the details.
• Such methods are implemented in subclass rather than super class
• A method which does not contain any definition in the
superclass is termed as abstract method.
• A class containing at least one abstract method is called as
abstract class
• Abstract classes can not be instantiated, that is one cannot create
an object of abstract class.
Contd….
43
abstract returntype name(parameter-list);

• As you can see, no method body is present.


• Any class that contains one or more abstract methods must also be
declared abstract.
• To declare a class abstract, you simply use the abstract keyword in
front of the class keyword at the beginning of the class declaration.
abstract class A 44
{
abstract void display(); //abstract method no definition
void show()
{
System.out.println(“class A show method");
}
}
class B extends A
{
void display()
{
System.out.println(“Class B display method");
}
}
class AbstractDemo
{ 45
public static void main(String args[])
{
A a =new A(); //error
B b = new B(); //subclass object
b.display(); //calling abstract method
b.show(); //calling concrete/normal method
}

}
Using final with Inheritance 46

• The keyword final has three uses


• First, it can be used to create the equivalent of a named
constant.
• The other two uses of the final apply to inheritance.

1. Using final to Prevent Overriding


2. Using final to Prevent Inheritance
final Prevents Overriding…. 47

• To prevent a method from being overridden, specify final as a


modifier at the start of its declaration. Methods declared as final
cannot be overridden.

• To disallow a method from being overridden, specify final as a


modifier at the start of its declaration.

• Methods declared as final cannot be overridden


class A
{ 48
final void meth()
{
System.out.println("This is a final method.");
}
}
class B extends A
{
void meth() // ERROR! Can't override.

{
System.out.println("Illegal!");
}
}
Using final to Prevent Inheritance ….
49
• Sometimes to prevent a class from being inherited.

• To do this, precede the class declaration with final.

• Declaring a class as final implicitly declares all of its


methods as final too.
final class A
{ // ...

}
// The following class is illegal.
class B extends A{// ERROR! Can't subclass A
// ...

}
As the comments imply, it is illegal for B to inherit A since A is declared as final
Local Variable Type Inference and
Inheritance 50

• A superclass reference can refer to a derived class object, and this


feature is part of Java’s support for polymorphism.
• when using local variable type inference, the inferred type of a
variable is based on the declared type of its initializer.
• Therefore, if the initializer is of the superclass type, that will be the
inferred type of the variable.
• It does not matter if the actual object being referred to by the
initializer is an instance of a derived class.
Local Variable Type Inference and
Inheritance 51

class MyClass
{
// ...
}
class FirstDerivedClass extends MyClass
{
int x;
// ...
}
class SecondDerivedClass extends FirstDerivedClass
{
int y;
// ...
}
Local Variable Type Inference and
Inheritance 52

class TypeInferenceAndInheritance
{
// Return some type of MyClass object.
static MyClass getObj(int which) {
switch(which) {
case 0: return new MyClass();
case 1: return new FirstDerivedClass();
default: return new SecondDerivedClass();
}
}
Local Variable Type Inference and
Inheritance 53

public static void main(String[] args) {


var mc = getObj(0);

var mc2 = getObj(1); // SecondDerivedClass object is returned.


var mc3 = getObj(2
//mc2.x = 10; // Wrong! MyClass does not have an x field.
// mc3.y = 10; // Wrong! MyClass does not have a y field.
}
}
Contd…
54
• In the program, a hierarchy is created that consists of three classes, at the
top of which is MyClass.
• FirstDerivedClass is a subclass of MyClass, and SecondDerivedClass is a
subclass of FirstDerivedClass.
• The program then uses type inference to create three variables, called mc,
mc2, and mc3 by calling getObj( ).
• The getObj( ) method has a return type of MyClass (the superclass), but
returns objects of type MyClass, FirstDerivedClass, or
SecondDerivedClass, depending on the argument that it is passed.
• the inferred type is determined by the return type of getObj( ), not by the
actual type of the object obtained. Thus, all three variables will be of type
MyClass.
The Object Class
55

• There is one special class, Object, defined by Java.


• All other classes are subclasses of Object.
• That is, Object is a superclass of all other classes. This means
that a reference variable of type Object can refer to an object of
any other class.
• Also, since arrays are implemented as classes, a variable of type
Object can also refer to any array.
The Object Class
56
Object defines the following methods, which means that they are
available in every object.
The Object Class
57
• The equals( ) method compares two objects.
• It returns true if the objects are equal, and false otherwise.
• The toString( ) method returns a string that contains a description
of the object on which it is called.
• Also, this method is automatically called when an object is
output using println( ).
• Many classes override this method. Doing so allows them to
tailor a description specifically for the types of objects that they
create.
• the return type for getClass( ). This relates to Java’s generics
feature

You might also like