Java Inheritance
Java Inheritance
• Single-level inheritance.
• Multi-level Inheritance.
• Hierarchical Inheritance.
• Multiple Inheritance.
• Hybrid Inheritance
• On the basis of class, there can be three types of inheritance in java:
Consider a scenario where A, B and C are three classes. The C class inherits A
and B classes.
If A and B classes have same method and you call it from child class object,
• We can only specify one superclass for any subclass that you create.
• Java does not support the inheritance of multiple super classes into a
single subclass. You can create a hierarchy of inheritance in which a
subclass becomes a superclass of another.
• However, no class can be a superclass of itself.
class A class Access {
{ public static void main(String args[]) {
int i; B subOb = new B();
private int j; subOb.setij(10, 12);
void setij(int x, int y) subOb.sum();
{ System.out.println("Total is " + subOb.total);
i = x; }
j = y; }
}
}
REMEMBER A class member that has been
class B extends A
{ declared as private will remain private to its
int total;
void sum()
class. It is not accessible by any code outside
{ its class, including subclasses.
total = i + j; // ERROR, j is not accessible here
Hierarchical Inheritance
• when a class has more than one child classes (sub classes) or in other
words more than one child classes have the same parent class then
this type of inheritance is known as hierarchical inheritance.
class A
class C extends A
{ {
public void methodA() public void methodC()
{ {
System.out.println("method of Class C");
System.out.println("method of Class A");
}
} }
} class JavaExample
class B extends A {
public static void main(String args[])
{
{
public void methodB() B obj1 = new B();
{ C obj2 = new C();
//All classes can access the method of class A
System.out.println("method of Class B");
obj1.methodA();
} obj2.methodA();
} }
}
output
• method of Class A
• method of Class A
Multi level Inheritance
class Shape
{ public void display() {
public class Tester {
System.out.println("Inside display"); public static void main(String[]
} arguments)
}
{
class Rectangle extends Shape {
public void area() Cube cube = new Cube();
{ cube.display();
System.out.println("Inside area");
cube.area();
}
} cube.volume();
class Cube extends Rectangle { }
public void volume()
{
}
System.out.println("Inside volume");
}
}