Inheritance without Compromising Encapsulation

Encapsulation is another very important concept in OOP that states, a class must hide its data from other software components and should not allow reading or writing instance attributes directly. And this access must be given via public get and set methods. (I would share the Encapsulation in separate article).

If you see the Student constructor, we have clearly violated the encapsulation principle for the inherited attributes by accessing those attributes directly. So a better design would making the ID and name attribute private in Person class and allow the subclasses to initialize them via parent class constructor. Lets see the updated code again:

package com.bitspedia.java.inheritance;

public class Person {
    private int ID;
    private String name;

    public Person() {
    }

    public Person(int ID, String name) {
        this.ID = ID;
        this.name = name;
    }

    public int getID() {
        return ID;
    }

    public void setID(int ID) {
        this.ID = ID;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

Lets See the updated subclass to that initialize the inherited attributes by calling constructor of the parent class.

package com.bitspedia.java.inheritance;

public class Student extends Person {
    private String courseName;
    private String advisor;

    public Student(int ID, String name, String courseName, String advisor) {
        super(ID, name);
        this.courseName = courseName;
        this.advisor = advisor;
    }  
}

Its much improved from earlier code of Student class. You see, we can call the parent class constructor using the super keyword by passing the parameters the parent class constructor expect. And did you noticed, I have also added get/set methods in Person class, why? Because constructor can be used only to initialize the inherited attributes. What if we need to read or updated their values later i.e. after the object creation? With public get/set methods, we can read and update inherited attributes values again in Student class. Another very important question is, which instance attributes and methods are inherited in subclass? I would discuss in next article.

Comments