Inheritance in Java

It is very similar to the topic of inheritance which you have learned in high school. Like children inherit some features or characteristics from their parents, So the same concept applies in the case of inheritance in java as well.

Advantages of Inheritance

  • Promotes code reusability

  • Reusability enhances reliability

Word extends is used to increase the functionality of existing child class, Now I would like to show some examples.

public class parent {
    int mother_age = 40;
    public void fun(){
        System.out.println("writer");
    }
}

public class child extends parent {
    int age = 15;
    public void play(){
        System.out.println("i play");
    }
    public static void main(String[] args) {
        child ch = new child();
        System.out.println(ch.mother_age);
        System.out.println(ch.age);
        ch.fun();
        ch.play();
    }
}

In the above example, I have used extends Key word after child, Which increases the functionality by inheriting all the methods and data variables from its parent class, like you can see we can easily access the variable mother_age and fun from parent's class by just creating an instance of class child.

the output of the above code is :

Note: If the child class has the same method as the parent class, then it will call its own method for example,

public class parent {
    public void fun(){
        System.out.println("writer");
    }
}
public class child extends parent {

    public void fun(){
        System.out.println("i play");
    }
    public static void main(String[] args) {
        child ch = new child();
        ch.fun();
    }
}

in the above example, it will call its own fun method and will print "i play " .

Note: every class by default inherits an Object class, Object class is the mother of all classes.

Apart from that, there are many types of inheritance in oops, but java can support only some like

  • Single level inheritance

  • Multilevel inheritance

  • hierarchical inheritance

Note: Java does not support Multiple & hybrid inheritance , lets take an example to understand the issue ,suppose there is a child class which extends both mother and father class and both classes have same method , so there will be ambiguity to call the methods of class mother and father. However this issue can be resolved by interfaces.