Inheritance is the process by which object of one class acquires the properties of the object of another class.
The class from which properties are inherited is called base class and the class to which properties are inherited is called derived class. The main feature of inheritance is the reusability of code we don’t have to write the same code again.
Types of inheritance:
- Single Inheritance
- Multiple Inheritance
- Multilevel Inheritance
- Hierarchical Inheritance
- Hybrid Inheritance
- Note: Multiple Inheritance is not supported in Java through class.
1. Single Inheritance: In a single inheritance the derived class is derived from a single base class. Let’s take an example.
class A { void add() { System.out.println("addition performed"); } } class B extends A { void sub() { System.out.println("subtraction performed"); } } class SingleInheritance { public static void main(String args[]) { B b=new B(); b.add(); b.sub(); } Output: addition performed subtraction performed
2. Multilevel Inheritance: In multilevel inheritance, class B is derived from class A and class C is derived from class B.
class A { void add() { System.out.println("addition performed"); } } class B extends A { void sub() { System.out.println("subtraction performed"); } } class C extends B { void mul() { System.out.println("multiplication performed"); } } class MultiLevelInheritance { public static void main(String args[]) { C c1=new C(); c1.add(); c1.sub(); c1.mul(); } } Output: addition performed subtraction performed multiplication performed
3. Hierarchical Inheritance: In hierarchical, multiple classes can be derived from a single base class.
class A { void add() { System.out.println("addition"); } } class B extends A { void sub() { System.out.println("subtraction"); } } class C extends A { void mul() { System.out.println("multiplication"); } } class HierarchicalInheritance { public static void main(String args[]) { C c=new C(); c.mul(); c.add(); } } Output: multiplication addition