Inheritance in java is a mechanism in which one object acquires all the properties and behaviors of parent object.
The class which inherits the properties of other is known as subclass (derived class, child class) and the class whose properties are inherited is known as superclass (base class, parent class).
Inheritance represents the IS-A relationship, also known as parent-child relationship.
Example of Single Inheritance
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Calculation{ | |
void adding(int a, int b){ | |
System.out.println("adding in super class: "+(a+b)); | |
} | |
} | |
class Calculation2 extends Calculation{ | |
void adding2(int a, int b){ | |
System.out.println("adding in sub class: "+(a+b)); | |
} | |
public static void main(String args[]){ | |
Calculation2 add = new Calculation2(); | |
add.adding(12,8); | |
add.adding2(12,8); | |
} | |
} | |
Example of Multilevel Inheritance
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Calculation{ | |
void adding(int a, int b){ | |
System.out.println("adding in super class: "+(a+b)); | |
} | |
} | |
class Calculation2 extends Calculation{ | |
void adding2(int a, int b){ | |
System.out.println("adding in Calculation2 class: "+(a+b)); | |
} | |
} | |
class Calculation3 extends Calculation2{ | |
void adding3(int a, int b){ | |
System.out.println("adding in Calculation3 class: "+(a+b)); | |
} | |
public static void main(String args[]){ | |
Calculation3 add = new Calculation3(); | |
add.adding(12,8); | |
add.adding2(10,8); | |
add.adding3(8,8); | |
} | |
} | |
Example of Heirarchical Inheritance
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class A{ | |
void displayA(){ | |
System.out.println(" This is a content of parent class"); | |
} | |
} | |
class B extends A{ | |
void displayB(){ | |
System.out.println(" This is a content of child class 1 B"); | |
} | |
} | |
class C extends A{ | |
void displayC(){ | |
System.out.println(" This is a content of child class 2 C"); | |
} | |
} | |
class Myclass{ | |
public static void main(String args[]){ | |
C c = new C(); | |
B b = new B(); | |
c.displayC(); | |
c.displayA(); | |
b.displayB(); | |
b.displayA(); | |
} | |
} |