INHERITANCE
Jyotiprakash Dash
Department of CSE
Introduction
• Inheritance in java is a mechanism in which one object acquires all the
properties and behavior of parent object.
• The idea behind inheritance in java is that you can create new classes
that are built upon existing classes.
• When you inherit from an existing class, you can reuse methods and
fields of parent class, and you can add new methods and fields also.
• A class that is inherited is called a superclass. A class that does the
inheriting is called a subclass.
• A subclass is a specialized version of a superclass that inherits all
instance variables and methods defined by the superclass and adds its
own, unique elements.
• Why use inheritance in java?
– For Method Overriding (so runtime polymorphism can be achieved).
– For Code Reusability.
• Syntax :
class Subclass-name extends Superclass-name
{
//Members
}
• Types of inheritance in java :
// Create a superclass. class SimpleInheritance
{ public static void main(String args[])
class A { A superOb = new A();
{ int i, j; B subOb = new B();
void showij()
// The superclass may be used by itself.
{ SOP("i &j: " + i + " " + j); superOb.i = 10;
} superOb.j = 20;
} SOP("Contents of superOb: ");
[Link]();
// Create a subclass by extending class /* The subclass has access to all public members
A. of its superclass. */
subOb.i = 7;
class B extends A
subOb.j = 8;
{ int k; subOb.k = 9;
void showk() SOP("Contents of subOb: ");
[Link]();
{ SOP("k: " + k); }
[Link]();
void sum()
{SOP ("i+j+k: " + (i+j+k)); } SOP("Sum of i, j and k in subOb:");
[Link]();
}
}
}
“super”-A keyword
To call super class constructor using subclass constructor
// Create a superclass. class SimpleInheritance
class A { public static void main(String args[])
{
{ int m, n;
A obj1= new A(10, 20);
A(int x, int y)
{m=x; n=y; } B obj2= new B(10, 20, 30);
void sum_mn()
{ SOP(m+n); } obj1.sum_mn();
obj2.sum_mnp();
}
class B extends A }
{ int p; }
B(int a, int b, int c)
{ super(a,b); p=c;}
void sum_mnp()
{ SOP(m+n+p); }
}
Constructor in Inheritance
• Constructor cannot be inherited by subclass.
• Super class constructor called first when constructor for subclass is invoked.
• Eg:
Class A
{ A(){ SOP(“Inside A’s Constructor….”); }
}
Class B extends A
{ B(){ SOP(“Inside B’s Constructor….”) ; }
}
Class C extends B
{ C(){ SOP(“Inside C’s Constructor….”) ; }
}
Class cons
{ P.S.V.M(String args[])
{
C c1=new C();
}
}
Method Overriding
• If subclass (child class) has the same method as declared in the parent
class, it is known as method overriding in java.
• Usage:
– used to provide specific implementation of a method that is already
provided by its super class.
– used for runtime polymorphism
• Rules:
– method must have same name as in the parent class
– method must have same parameter as in the parent class.
– inheritance relationship
//METHOD OVERIDE EG.
class Overide
{
class A public static void main(String args[])
{ void show() {
{ …… B b_obj = new B( );
…… b_obj. show( );
……
A a_obj = new B( );
} a_obj. show( );
}
class B extends A }
}
{ void show()
{ ……
……
……
}
}
//2nd USE OF SUPER
class Overide
class A {
public static void main(String args[])
{ void show()
{
{ ……
B b_obj = new B( );
……
b_obj. show( );
……
} A a_obj = new B( );
} a_obj. show( );
class B extends A [Link]( ); //NOT ALLOWED
{ void show()
{
…… }
[Link]( ); }
……
……
}
}
//3rd USE OF SUPER
class Overide
class A {
{ int x, y; public static void main(String args[])
void show() {
{ …… B b_obj = new B( );
…… b_obj. show( );
……
A a_obj = new B( );
} a_obj. show( );
}
class B extends A }
{ int x, z; }
void show()
{
SOP(x);
……
……
SOP(super.x);
}
}
A Superclass Variable Can Reference a Subclass Object
class A class Overide
{ void show() { public static void main(String args[])
{ …… { A a_obj = new A( );
B b_obj = new B( );
……
C c_obj = new C( );
}
} a_obj. show( );
class B extends A b_obj. show( );
{ void show() c_obj. show( );
{ …… }
…… }
}
void display() A
{ …… Show( )
}
}
class C extends A B C
{ void show() Show( ) Show( )
{ …… Display( )
}
}
A Superclass Variable Can Reference a Subclass Object
class A class Overide
{ void show() { public static void main(String args[])
{ …… { A a_obj = new A( );
B b_obj = new B( );
……
C c_obj = new C( );
}
} a_obj. show( );
class B extends A b_obj. show( );
{ void show() c_obj. show( );
{ ……
…… A ar;
}
void display() ar = a_obj;
[Link]( );
{ ……
} ar= b_obj ;
} [Link]( );
class C extends A
{ void show() ar= c_obj ;
{ …… [Link]( );
} }
} }
A Superclass Variable Can Reference a Subclass Object
class A class Overide
{ void show() { public static void main(String args[])
{ …… { A a_obj = new A( );
…… B b_obj = new B( );
} C c_obj = new C( );
}
class B extends A a_obj. show( );
{ void show() b_obj. show( );
{ …… c_obj. show( );
……
} A ar;
void display()
{ …… ar = a_obj;
} [Link]( );
}
class C extends A ar= b_obj ; //super class ref. subclass obj
{ void show() [Link]( );
{ …… ar. display( ); //ERROR
} }
} }
NOTE: when a reference to a subclass object is assigned to a superclass reference variable,
you will have access only to those parts of the object defined by the superclass.
RECAP
• Using super
– Using super to Call Superclass Constructors
Eg: super(arg-list);
– A Second Use for super
Eg: [Link]
• Creating a Multilevel Hierarchy / Hierarchical
• A Superclass Variable Can Reference a Subclass Object
• Method Overriding
• Dynamic Method Dispatch
Dynamic Method Dispatch
• Dynamic method dispatch is a concept. (Method overriding &
Super class reference variable)
• It is the mechanism by which a call to an overridden method is
resolved at run time, rather than compile time.
• Dynamic method dispatch is important because this is how Java
implements run-time polymorphism.
• 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. Thus, this determination is made at run time.
// Dynamic Method Dispatch class Dispatch
{ P.S.V.M (String args[])
class A {
{ A a = new A(); // object of type A
void callme()
B b = new B(); // object of type B
{ SOP("Inside A's method"); }
}
C c = new C(); // object of type C
A r; // obtain a reference of type
class B extends A
{ r = a; // r refers to an A object
void callme() [Link](); // calls A's version of callme
{ SOP("Inside B's method"); }
} r = b; // r refers to a B object
[Link](); // calls B's version of callme
class C extends A
{
r = c; // r refers to a C object
void callme() [Link](); // calls C's version of callme
{ SOP("Inside C's method"); } }
} }
Abstract class in Java
• Abstraction is a process of hiding the implementation details and showing
only functionality to the user. Eg: sms
• A class that is declared with abstract keyword, is known as abstract class
in java.
• It can have abstract and non-abstract methods (method with body).
• There are two ways to achieve abstraction in java
– Abstract class
– Interface
• An abstract class needs to be extended and its method to be
implemented. Example: abstract class A{}
• Abstract method: A method that is declared as abstract and does not
have implementation is known as abstract method.
Eg: abstract void printStatus();
Example of abstract
abstract class Bike
{
abstract void run();
}
class Honda4 extends Bike
{
void run()
{[Link]("running safely..");}
public static void main(String args[])
{
Bike obj = new Honda4();
[Link]();
}
}
Rules
• Any class that contains one or more abstract
methods must also be declared abstract.
• An abstract class cannot be directly instantiated
with the new operator (because an abstract class is
not fully defined).
• Cannot declare abstract constructors, or abstract
static methods.
• Any subclass of an abstract class must either
implement all of the abstract methods in the
superclass, or be itself declared abstract.
Example
class AbstractDemo
abstract class A
{ {
abstract void callme(); public static void main()
void callmetoo() {
{ B b = new B();
SOP("concrete method.");
[Link]();
}
} [Link]();
}
class B extends A }
{
void callme()
{
SOP("B's callme.");
}
}
Note:
• No objects of class A are declared in the program
• Abstract classes can be used to create object references
• Class A implements a concrete method called callmetoo( ). It’s perfectly acceptable
abstract class Figure class AbstractAreas
{ double dim1; double dim2; {
Figure(double a, double b) PSVM(String args[])
{ dim1 = a; dim2 = b; }
abstract double area(); {
} // Figure f = new Figure(10, 10);
class Rectangle extends Figure Rectangle r = new Rectangle(9, 5);
{ Rectangle(double a, double b) Triangle t = new Triangle(10, 8);
{ super(a, b); }
double area()
{ SOP("Area for Rectangle."); // this is OK, no object is created
return dim1 * dim2; Figure figref;
}
} figref = r;
class Triangle extends Figure SOP("Area is " + [Link]());
{ Triangle(double a, double b)
{ super(a, b); }
double area() figref = t;
{ SOP("Area for Triangle."); SOP("Area is " + [Link]());
return dim1 * dim2 / 2; }
} }
} All subclasses of Figure must override area( ).
“Final”-A Keyword
• The final keyword in java is used to restrict the user.
• Final keyword usage: variable, method & class
1. final variable: If you make any variable as final, you cannot change the
value of final variable(It will be constant).
Eg: class Bike9
{ final int speedlimit=90;
void run()
{ speedlimit=400; }
public static void main(String args[])
{
Bike9 obj=new Bike9();
[Link]();
}
}
Using final with Inheritance
1. 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
• Example: class A
{ final void meth()
{[Link]("This is a final method.");}
}
class B extends A
{ void meth() // ERROR! Can't override.
{ [Link]("Illegal!"); }
}
Note:
• Because meth( ) is declared as final, it cannot be overridden in B. If you
attempt to do so, a compile-time error will result.
• Java resolves calls to methods dynamically, at run Time (Late binding).
However, since final methods cannot be overridden, a call to one can be
resolved at compile time. (Early binding)
Using final with Inheritance
• To prevent a class from being inherited, precede the class declaration
with final.
• Declaring a class as final implicitly declares all of its methods as final,
too.
• Example:
final class A
{ // ... }
class B extends A
{ // ERROR! Can't subclass A
// ...
}
• It is illegal for B to inherit A since A is declared as final.