Java Inheritance

Inheritance is the methodology by which a class inherits the properties and functionalities of another class. So, if class A is inherited from class B, then class A automatically receives the capabilities of class B. This is also an example of code reuse - class B code is reused in class A.

In real life, a class may be a descendant of another class. For example, the Student class is inherited from the Person class. A student is a person, but all persons are not students. A person is a superclass, and a Student is a subclass.

The basic idea behind inheritance stems from two important concepts - code reuse and object hierarchy. If class A holds all the properties of class B and it has some more properties of its own, then we may think of reusing class B when constructing class A.

This means class A inherits all members of class B by default and is also allowed to add more as per the need of the class. This forms a class hierarchy. Inheritance is a use case of code reuse.

We have discussed the following new concepts related to inheritance.

  1. super class – the class from which another class is inherited or derived. It is also termed a base class or parent class. In Ex. 8 CreditCard is the superclass. It has been extended to Regular class and the super keyword has been used to access the superclass constructor.
  2. sub class – the class which inherits another class. It is also termed derived class, extended class, or child class. In Ex. 8 Regular class is the subclass. In addition to superclass member variables and methods, a subclass can also add its own variables and methods for the additional functionalities.
  3. extends – the keyword extends is used to inherit a class from another class.

Inheritance and encapsulation

Inheritance and encapsulation work together. We have seen that a subclass inherits all the attributes of its superclass. Therefore, all the members that have been encapsulated in the parent remain encapsulated even in the child class, and this way, the encapsulation is carried on. This helps in handling the complexity of programs that grow in size.Types of Inheritance

1. Single Inheritance – A Child or Derived class inherits its Parent or Base class. This may be represented as Parent -> Child. The following example shows the inheritance of a Child from a Parent and the accessibility of the base class member variable and method from the derived class. Parent class members are also accessible from a Parent object.

Java Inheritance-Parent Child
			



// This example shows the single inheritance of a Child class from its Parent
//
class Parent{
    int x = 10;
    void printParent() {System.out.println("Parent");}
}
class Child extends Parent{
    int y = 20;
    void printChild() {System.out.println("Child");}
}
class Test{
    public static void main(String[] args){
        Parent p = new Parent();
        p.printParent();            // parent method accessed from Parent object
        Child c = new Child();      
        System.out.println(c.x);    // parent variable accessed from Child object
        c.printParent();            // parent method accessed from Child object
        System.out.println(c.y);    // child variable accessed from Child object
        c.printChild();             // child method accessed from Child object
    }
}

				

Output:

Parent 10 Parent 20 Child

2. Multilevel Inheritance - In Multilevel Inheritance, a derived class may also act as a base class for another class derived from it. Here the representation is Parent -> Child -> Grandchild. What is the max level of inheritance in Java? A natural query. The answer is there are no specifications in the language, but it may be implementation dependant.

Java Inheritance Parent Child  Grand Child
			

//  This example shows multilevel inheritance Parent -> Child -> Grandchild
 
class Parent {
    public void printGrandfather(){ System.out.println("Grand Father"); }
}
 class Child extends Parent {
    public void printFather() { System.out.println("Father"); }
}
 class Grandchild extends Child {
    public void printGrandson() { System.out.println("Grand son"); }
}
 public class Main {
    public static void main(String[] args)
    {
        Grandchild g = new Grandchild();
        g.printGrandfather();   //  Accessing super of super class method
        g.printFather();        //  Accessing super class method
        g.printGrandson();      //  Accessing own class method
        Child c = new Child();  
        c.printFather();
        c.printGrandfather();
        Parent p = new Parent();
        p.printGrandfather();
    }
}

				

Output:

Grand Father Father Grand son Father Grand Father Grand Father

3. Hierarchical Inheritance - In Hierarchical Inheritance, one class acts as a super class or base class for more than one subclass or derived class.

ava Hierarchical Inheritance

Let us take the following hypothetical example to explain this. The application under consideration is Credit Card of a specific bank. The study reveals that the bank offers three types of credit cards – regular, gold and premium.

Each type of card has some common properties like card number, name of the cardholder, customer phone number, customer address, customer email id, date of issue, date of expiry, CVV, and credit limit.

The actions of the card include – spendMoney, depositMoney, generateStatement, addCustomer, deleteCustomer, activateCard, deactivateCard etc. These are the standard set of properties and actions required for all card types and can be considered at Credit Card level. But each type of card has some specifics, which are unique differentiators.

Let us say Regular type offers product discounts in POS, Gold type offers fuel discounts, and Premium offers fuel discounts, and cashbacks. We develop the parent class CreditCard, and extend this class to three new classes as shown in the class hierarchy.

When we design a parent class, we must factor out the commonalities of various child classes of that parent.  Once the parent is created, the child classes can be created by extending it further. This adds more elegance and readability to the class design. To illustrate this, The below example shows a very novice implementation of the parent class CreditCard and one child class Regular derived from the parent. 

Hierarchical Inheritance of a Credit Card Application.

			

class CreditCard{
    // This class has 5 member variables and one method. 
    // It has one Constructor which takes 5 arguments
    String cardHolder;
    String cardNumber;
    int cvv;
    String expiry;
    int creditLimit;
    CreditCard (String cardHolder, String cardNumber, int cvv, String expiry, int creditLimit)
    //  Constructor function
    {
        this.cardHolder = cardHolder;
        this.cardNumber = cardNumber;
        this.cvv = cvv;
        this.expiry = expiry;
        this.creditLimit = creditLimit;
    }
    void displayCard()
    {
        System.out.println("Card Holder Name: "+cardHolder);
        System.out.println("Card Number: "+cardNumber);
        System.out.println("CVV: "+cvv);
        System.out.println("Expiry: "+expiry);
        System.out.println("Credit Limit: "+creditLimit);
    }
}
class Regular extends CreditCard{
    double discount_pos;
    Regular (String cardHolder, String cardNumber, int cvv, String expiry, int creditLimit, double discount_pos) {
        super(cardHolder, cardNumber, cvv, expiry, creditLimit);
        this.discount_pos = discount_pos;
    }
    @Override void displayCard()  // The superclass method has been overwritten by the child class
    {
        super.displayCard();
        System.out.println("Discount percentage: "+discount_pos);
    }
}
class Test {
    public static void main(String args[])
    {
        CreditCard cc = new CreditCard("A. Choudhury", "816517000002456", 256, "04/23", 300000);
        cc.displayCard();

        Regular rcc = new Regular("G.M. Basu", "6290600100013546", 577, "09/22", 550000, 4.75);
        rcc.displayCard();

    }
}