Inheritance
Inheritance
Inheritance
Inheritance
• Inheritance allows us to use one class by another class.
• Syntax:
class sub_class_name extends super_class
{
//body of the sub class.
}
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();
}
}
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.
• 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.
class Override
{
public void display()
{
System.out.println("Hello...This is superclass display");
}
}
r = b; // r refers to a B object
r.callme(); // calls B's version of callme
public AbstractClassExample()
{
x = 0;
}
}
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);