Inheritance In Java

Inheritance In Java

Today we will learn about Inheritance in Java. What is Inheritance in a general way or non-programming way? It’s basically the transfer of some properties from parent generation to child generation. But is child exact copy of parent generation? No! child has some variations and some own properties.

Inheritance in Java works in same way. When the need of hour is to create a class which uses the properties of some other class and also have some of its own properties, we use Inheritance as a property of OOPs.

How we use it?

Assume you have a class which contains the data of very marks of students in English, Mathematics and History. Now you want to create another class which have marks of another two subjects Physics and Chemistry, also you want to get the percentage of student. How will you achieve it? You might be thinking of many ways but today we will solve this by inheritance. So basically, we have a primary class which contains marks of first three subjects. Let’s say this class as Parent.

static class Parent{

    double English;

    double Mathematics;

    double History;

}

}

Now we want to create a class which uses the properties of this class that is marks of these three subjects and also have marks of other two subjects and finally we want to calculate percentage. This means we want to inherit this class and for this we use extends keyword. So, this is the way of inheriting a class: class_ChildClassName_extends_ParentClassName. Let’s create this class!

static class Child extends Parent{

    double Physics;

    double Chemistry;

}

What does this mean? This simply means this:

static class ChilDEquivalence{

        double English;

        double Mathematics;

        double History;

        double Physics;

        double Chemistry;

}

Creating And Accessing objects for Parent and Child Class

Creating object for parent class is very simple and nothing new is there because it’s just another normal class.

But interesting case is creating object for Child class.

Let’s create an object for Child class!

public static void main(String[] args) {

    Child stud1=new Child();



}

Now we didn’t add Mathematics in child class, but will we able to set and then access it through child? Let’s see!

public static void main(String[] args) {

    Child stud1=new Child();

    stud1.Mathematics=95;

    System.out.println(stud1.Mathematics);

}

Yes! We are able to do this! It’s just like that Mathematics is existing in Child class. But can we do opposite? Means accessing child properties through parent class (isn’t it seeming illogical)

public static void main(String[] args) {

    Child stud1=new Child();

    stud1.Mathematics=95;

    System.out.println(stud1.Mathematics);

    Parent stud=new Parent();

    stud.Physics=56;

}

When you will try to execute this code, error will be there! This means:

Parent class is unknown of any property present inside child class.

Note: The private members of parent class are only accessible to parent class only, they can’t be accessed by child class even.

Calling Constructor of Parent Class in Child Class

Let’s firstly create a constructor in Parent Class:

static class Parent{

    double English;

    double Mathematics;

    double History;

    Parent(double English,double Mathematics, double History){

        this.Mathematics=Mathematics;

        this.English=English;

        this.History=History;

    }

}

When you will be creating this constructor then you would see an error for child class: There is no default constructor available in 'Inheritance.Parent'

We will answer the reason for this error at the end of this blog. Let’s just firstly call constructor in the child class. For calling the constructor or any property of Parent class we use super keyword. This is how we will call the constructor:

static class Child extends Parent{

    double Physics;

    double Chemistry;

    Child(double History, double Mathematics, double English, double Physics, double Chemistry){

        super(English,Mathematics,History);

        this.Physics=Physics;

        this.Chemistry=Chemistry;

    }



}

The super here will call the constructor of Parent Class.

Note: super should be the first execution inside the class!

Fact: super keyword calls the variables of closest class. Take this example, if we have three classes, A,B and C where C is child of B and B is child of A, so when you will use super in C, it will move to class B not A as the closest class to it is B!

Need of super:

You will notice that if you use this keyword instead of super keyword while calling the variables of parent class, it will work! (Not in the case of constructor, obviously!). See this code:

public class Inheritance {

    public static void main(String[] args) {

     Child student=new Child(55,63,78,95,84);

        System.out.println(student.example(96));

    }

    static class Parent{

        double English;

        double Mathematics;

        double History;

        Parent(double English,double Mathematics, double History){

            this.Mathematics=Mathematics;

            this.English=English;

            this.History=History;

        }

    }

    static class Child extends Parent{

        double Physics;

        double Chemistry;

        Child(double History, double Mathematics, double English, double Physics, double Chemistry){

            super(English,Mathematics,History);

            this.Physics=Physics;

            this.Chemistry=Chemistry;

        }

        double example(double EnglishCopy){

            this.English=EnglishCopy;

            return EnglishCopy;

        }



    }



}

See the example method in code, we have used this keyword and it is running very fine. We can use super also instead of this by super.English but then what is the need of super. For that assume a case when you have two different properties in Parent and Child class with same name and in some place you want to call the property of Parent class and in other you want to call that of Child class. What will you do then, say property name is sameName, so for calling property of Parent class you will use super keyword and for calling the same class you will use this keyword.

Playing with Objects

public class Inheritance {

    public static void main(String[] args) {

     Child student1=new Child(55,63,78,95,84);

     Parent student2=new Parent(56,29,33);

     Parent student3=new Child(55,26,63,97,65);

     Child student4=new Parent(45,63,89);

    }

    static class Parent{

        double English;

        double Mathematics;

        double History;

        Parent(double English,double Mathematics, double History){

            this.Mathematics=Mathematics;

            this.English=English;

            this.History=History;

        }

    }

    static class Child extends Parent{

        double Physics;

        double Chemistry;

        Child(double History, double Mathematics, double English, double Physics, double Chemistry){

            super(English,Mathematics,History);

            this.Physics=Physics;

            this.Chemistry=Chemistry;

        }



    }



}

Here we have form objects by 4 permutations, can you tell which will work and which will not? If you will see in logical manner, it is very simple. In first case you are creating an object of Child type and calling the constructor of Child class so it will run very smoothly, same is the second case. In third case the object is of type Parent but constructor is of child, so it will also run very smoothly as constructor will be able to access all the members of Parent class but there will be a problem, what if you want to access student3.Physics? Will you able to do that? No! because student3 is type of parent class and parent class don’t have any knowledge of child class but the fact is when you used the child constructor, you initialised every variable but you can’t access them all! Now let’s see the fourth case, when object is of type child and constructer called is of Parent type. Will this run? A hell no! Reason is very simple and obvious you will not be able to initialise each member of child class but when object is created its members should be initialised. Think in this way, assume you are language and you have to give output when someone asks for student4.Physics, what will you do? Physics is contained in child class but it is not initialised, hence it is totally wrong. In third case you could easily say that Physics is not contained in Parent class but you can’t say this here and as you are language you can’t give excuse!

Answer to the Error:

In middle I said that you will encounter an error There is no default constructor available in 'Inheritance.Parent'

At that time, I said you to create a constructor in child class but now let’s explore this error!

Assume that both parent and child class don’t have constructor, so this will run smoothly because while creating object when you will call child/parent constructor it will run just like another normal class.

Now assume Parent class have constructor while child class don’t. What will happen now? It will give the above error. Now do one thing create a constructor in parent class which don’t take any argument. It will solve the error. For understanding this let’s move to very basics of Inheritance. What does inheritance do? It takes the properties of Parent class and inject it into child class. That means in this case an Equivalent Child class will be:

class ChildEquivalence{

    double English;

    double Mathematics;

    double History;

    double Physics;

    double Chemistry;

    ChildEquivalence(double Emglish,double Mathematics, double History, double Physics, double Chemistry){

        this.English=Emglish;

        this.Mathematics=Mathematics;

        this.History=History;

        this.Physics=Physics;

        this.Chemistry=Chemistry;

    }

}

This means when child class has no constructor and parent class has, child class call the constructor of Parent Class. Now if you want to create an object for this equivalent class you have to call constructor, but it’s obvious now that you can’t call an argument-less constructor. Same is the case when you use inheritance. When parent class have an argumented constructor and child class have no constructor then on creation of object for child class when you will call default constructor of it, child class will call default constructor of Parent class but now Parent class don’t have any default constructor, hence you will not be able to create an object. That’s why when we create a default constructor in Parent class, this error gets resolved or we can also solve this error by creating a default/argumented constructor for child class, so that during creating object, the constructor of child class is invoked.

I hope that now Inheritance is felt by you! If there is any problem and suggestions then do comment!