Programming |
The process of acquiring properties and behavior of a class by another class is called inheritance. Inheritance is an important feature of Object-Oriented Programming.
Advantages of Inheritance
Properties of Inheritance
Syntax
class SubClass extends SuperClass{ statements }
Syntax
class SubClass implements SuperInterface{ statements }
Types of Inheritance
1. Simple inheritance
When a class inherits from only one superclass
Program
class A { void doStuff() { System.out.println("Doing Stuff."); } } class B extends A { void sleep() { System.out.println("Sleeping."); } } public class SimpleInheritance { public static void main(String args[]) { B b = new B(); b.doStuff(); b.sleep(); } }
2. Multiple inheritance(Through Interfaces)
When a class can inherits properties and behaviors of multiple interfaces. Java does not support multiple inheritance through classes.
Program
interface A { public void run(); } interface B { public void walk(); } interface C extends A, B { public void run(); } class child implements C { @Override public void run() { System.out.println("Running."); } public void walk() { System.out.println("Walking."); } } public class MultipleInheritance { public static void main(String[] args) { child c = new child(); c.run(); c.walk(); c.run(); } }
3. Multilevel inheritance
When class A is extending a class B which itself is extending another class C, it is known as multilevel inheritance. In this, class A can extend the properties and behavior of both class B and class C.
Program
class A { void doStuff() { System.out.println("Doing Stuff."); } } class B extends A { void sleep() { System.out.println("Sleeping."); } } class C extends B { void walk() { System.out.println("Walking."); } } public class MultilevelInheritance { public static void main(String args[]) { C c = new C(); c.doStuff(); c.sleep(); c.walk(); } }
4. Hierarchical inheritance
In this type of inheritance one superclass can have multiple direct sub-classes.
Program
class A { void doStuff() { System.out.println("Doing Stuff."); } } class B extends A { void sleep() { System.out.println("Sleeping."); } } class C extends A { void walk() { System.out.println("Walking."); } } public class HierarchicalInheritance { public static void main(String args[]) { B b = new B(); b.doStuff(); b.sleep(); C c = new C(); c.doStuff(); c.walk(); } }
5. Hybrid inheritance
Hybrid inheritance is a combination of more than one type of inheritance described above.
6. Cyclic inheritance
When a class is extending itself then it is known as cyclic inheritance. Cyclic inheritance is not supported in java.