How Inheritance Works in Java - Basic Sample Code

I hope you have well understood the basic objective and benefits of using inheritance from my previous article, in this article we would see simple example code.

Let us assume we are building an information system to manage different operations in an academic institution. It would involve different type of entities e.g. students, teachers, managers, etc. Lets define a general component i.e. Person first, the Person class would hold the common attributes of different type of related entities. Lets see how it would look like:


public class Person {
    int ID;
    String name;

We have defined ID and name attribute because these are common among student, teacher and manager. So we can create Student class by inheriting it from Person class. In this way we add only those attributes in Student which are not present in Person class. Because, the attributes in Person class would be inherited in Student class. Here is the student class:


public class Student extends Person {
    String courseName;
    String advisor;
    public Student(int ID, String name, String courseName, String advisor) {
        this.ID = ID; = name;
        this.courseName = courseName;
        this.advisor = advisor;

The extends keyword in class declaration performs the actual inheritance. See, we have received values of all attributes of Student in constructor, local and inherited both. And we have accessed ID and name attribute using this operator, though both attributes actually belong to parent class. So this is clear indication, the inherited attributes becomes the attributes of subclass, and can be used just like other attribute of the Student class, though they are actually defined in parent class.

There must be IS-A relation in subclass and parent class. It helps defining correct inheritance hierarchy. In above example, we can say, Student IS-A Person. If you have class Cat that extends Animal, we can say, Cat IS-A Animal. But you should never make an inheritance relation between two classes where IS-A relations does not hold true, e.g. defining a Chair class that extends Animal is incorrect as Chair IS-A Animal is incorrect.

The super class of all classes in Java is Object class. Our classes are always subclass of Object, so we generally omit to inherit from Object, as its done implicitly. So we can use methods inherited from Object class. The IS-A relation hold between subclass and its parent classes, whether they are direct parent or indirect parent classes.

The above code is very basic example of inheritance, from good software design perspective, we should inherit attributes in such a way that do not violate the encapsulation principle. I have discussed it in detail Inheritance without Compromising Encapsulation.