Inheritance is an important feature of any Object-Oriented programming language. With the help of inheritance, a class can inherit the properties(variables) and behavior(methods) of another class. The class that inherits from another class can also define additional members.
The class that inherits the another class is called derived class, child class, or subclass. The class from which you derive your class is known as base class, parent class, or superclass.
A class uses extends keyword to inherit a class. Inheritance is used to show is-a relationship.
Note- Private members and constructors of a base class are never inherited.
Syntax
class DerivedClass extends BaseClass { //Properties and Behaviour }
Java supports three types of inheritance which are listed below-
Note- Java does not support Multiple and Hybrid inheritance but with the help of interface, you can implement it.
class Father { public void fatherIdentity() { System.out.println("I am a Father."); } } class Son extends Father { public void sonIdentity() { System.out.println("I am a Son."); } } class Test { public static void main(String args[]) { Son s = new Son(); s.sonIdentity(); s.fatherIdentity(); } }
Output
I am a Son. I am a Father.
class Father { public void fatherIdentity() { System.out.println("I am a Father."); } } class Son extends Father { public void sonIdentity() { System.out.println("I am a Son."); } } class GrandSon extends Son { public void grandsonIdentity() { System.out.println("I am a GrandSon."); } } class Test { public static void main(String args[]) { GrandSon s = new GrandSon(); s.grandsonIdentity(); s.sonIdentity(); s.fatherIdentity(); } }
Output
I am a GrandSon. I am a Son. I am a Father.
class Father { public void fatherIdentity() { System.out.println("I am a Father."); } } class Son extends Father { public void sonIdentity() { System.out.println("I am a Son."); } } class Daughter extends Father { public void daughterIdentity() { System.out.println("I am a Daughter."); } } class Test { public static void main(String args[]) { Son s = new Son(); s.sonIdentity(); s.fatherIdentity(); Daughter d = new Daughter(); d.daughterIdentity(); d.fatherIdentity(); } }
Output
I am a Son. I am a Father. I am a Daughter. I am a Father.
The reason is that a derived class may inherit the same method with different implementation from multiple base classes, this will create ambiguity in calling the method.
Let's take an example to understand the problem. There are three classes X, Y, and Z. Class Z inherits X and Y. Both classes X and Y have the same method which is show() and when an object of class Z calls show() method will give compile time error.
class X { public void show() { System.out.println("class X show method"); } } class Y { public void show() { System.out.println("class Y show method"); } } class Z extends X,Y { public static void main(String args[]) { Z z = new Z(); z.show(); } }
Output
Compile Time Error