L7 Inheritance
L7 Inheritance
Inheritance
By
Arvind Kumar
Asst. Professor, LPU
Blank
Inheritance
• Inheritance allows us to use one class by another class.
• Syntax:
class sub_class_name extends super_class
{
//body of the sub class.
}
Blank
class A
{ int i, j;
void showij()
{
System.out.println("i and j: " + i + " " + j);
} }
class B extends A
{int k;
void showk()
{ System.out.println("k: " + k); }
void sum()
{ System.out.println("i+j+k: " + (i+j+k)); }
public static void main(String args[])
{B r=new B();
r.sum();
}
}
Blank
Multilevel Inheritance
• It is the enhancement of the concept of inheritance. When a
subclass is derived from a derived class then this mechanism
is known as the multilevel inheritance.
• The derived class is called the subclass or child class for it's
parent class and this parent class works as the child class for
it's just above (parent) class.
• One of these would exist in the base class and another in the
derived class. These cannot exist in the same class.
Blank
• The version of a method that is executed will be determined
by the object that is used to invoke it.
• Within a class, a field that has the same name as a field in the
superclass hides the superclass's field, even if their types are
different. Within the subclass, the field in the superclass
cannot be referenced by its simple name.
Blank
class Override
{
public void display()
{
System.out.println("Hello...This is superclass display");
}
}
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
}
}
Blank
Accessing Superclass Members
• If your method overrides one of its superclass's methods, you
can invoke the overridden method through the use of the
keyword super.
Blank
class Superclass
{ public void printMethod()
{
System.out.println("Printed in Superclass.");
}
}
class Subclass extends Superclass
{ // overrides printMethod in Superclass
public void printMethod()
{
super.printMethod();
System.out.println("Printed in Subclass");
}
public static void main(String[] args)
{ Subclass s = new Subclass();
s.printMethod();
}}
Blank
Using super
• A subclass can call a constructor defined by its superclass by
use of the following form of super:
super(arg-list);
public AbstractClassExample()
{
x = 0;
}
}
Blank
abstract class Shape{
public static float pi = 3.142f; protected float height; protected float
width; abstract float area() ;}
class Square extends Shape{
Square(float h, float w){height = h; width = w;}
final float area(){return height * width;}}
class FinalMethodDemo
{
public static void main(String args[])
{
Square sObj = new Square(5,5);