Inheritance in Java

Beginners Code Computer Skills Java

Now that you are aware of the basic terminology of OOps in Java, its time to learn about each of them. Well, the members of the different classes can be accessed in 2 ways i.e. by Aggregation and the next is by Inheritance in java.

Aggregation in Java:

  • Without any relation between the 2 classes, one class can access the resources of the other class through aggregation.
  • It is simply by creating objects of other classes and calling their methods.
  • But the problem of aggregation is the user can access the resource but cannot modify it. This problem is solved by inheritance.
package mypackage;

public class AClass {
  public int a = 9;
}
package mypackage;

public class BClass {
  public int b = 16;
}
package mypackage;

public class TestAB {
  
  public static void main(String[] args) {
    
    AClass obj1 = new AClass();
    System.out.println("Value of a from AClass: " + obj1.a);
    BClass obj2 = new BClass();
    System.out.println("Value of b from BClass: " + obj2.b);
  }
}

Output:

Aggregtion

Inheritance in Java:

  • With a relation between the 2 classes, one class can access the resource of the other is the concept of inheritance.
  • Inheritance is the ability of a class to inherit some data and behavior from other related classes.
  • The relation between 2 .class files in Java is only possible by 2 keywords:
    • extends
    • implements
Super ClassSuper Interface
Sub Classextendsimplements
Sub Interfacenot possibleextends

Fundamental characteristics of Inheritance in Java:

  • It is a technique of sharing properties of the base class within the child class.
    • It helps to group or categorize classes through a parent-child relationship.
  • The child class will inherit all the properties, data and method of the parent class as well as have some new properties of its own.
  • For Example,
    • Suppose Animals is the parent class.
    • Let Dog class and Cat class be its child classes.
    • We all know that Dog and Cat exhibit all the characteristics of class Animals and still have some additional characteristics of their own.
      inheritance Animal class
  • Private properties of the base or parent class are not inherited by the child class.
  • Instances or objects of a child class can access the data and methods of the parent class.
  • Inheritance is transitive. Thus subclasses inherit features from a parent class anywhere up in the hierarchy.
  • Inheritance implies that one child class can be an extension of the parent class. 

Creating an inheritance:

The syntax to create an inheritance relation:

public class ChildClass extends ParentClass{}

When a user creates the object of a child class, Java compiler automatically creates objects of all the superclasses in case of inheritance.

package mypackage;

public class Base {

  int ab = 17;
  
  public Base() {
  
    System.out.println("Base class constructor");
  }
}

package mypackage;

public class Derived extends Base{
int a = 10;
  
  public Derived() {
    
    System.out.println("Derived class constructor");
    
  }
  
  public static void main(String[] args) {
    
    Derived obj = new Derived();
    System.out.println("Value of a is: " + obj.ab);
  }
}

inheritance base superclass called

From the above program, we can see one more important concept. If there is an ambiguity in the name of the variable, the object data of the child class is always printed.

Instances or objects of a child class can also modify the data and methods of the parent class.

package mypackage;

public class ParentClass {

  int a = 11;
  public int b = 7;
  int c = 71;
  
  private int d = 20;
  protected int e = 3;
  
}
package mypackage;

public class ChildClass extends ParentClass{
  
public static void main(String[] args) {
    
    ParentClass obj1 = new ParentClass();
    System.out.println("Value of a : " +o bj1.a);
    ChildClass obj2 = new ChildClass();
    System.out.println("Value of b : " + obj2.b);
    System.out.println("Value of e : " + obj2.e);
    
    System.out.println("Value of c before modifying: " + obj2.c);
    obj2.c = 8;
    System.out.println("Value of c after modifying: " + obj2.c);
      
  }
}

inheritance- modify parent class

In the above program, d is a private data variable of the class ParentClass and it throws an error if the derived class ChildClass tries to access the private variable d.

private variable error

 

Types of Inheritance in Java:

Java supports 5 types of inheritance.

  • Single inheritance
  • Multilevel inheritance
  • Hierarchical inheritance
  • Multiple inheritance ( through an interface )
  • Hybrid inheritance

Single inheritance:

  • Java classes by default support single level inheritance.
  • An object is a predefined class present in java.lang package. It is the superclass of all user-defined and predefined class in Java.
  • getClass() is a predefined method present in Object class which always returns the object of the current class.
  • getSuperclass() is a predefined method present in Object class which always returns the object of the nearest parent class.

single inheritance

Here is an example to show a single level inheritance.

package test;

public class SingleLevel {
  
  public static void main(String[] args) {
    
    SingleLevel s1 = new SingleLevel();
  
    System.out.println("s1 is oject of class SingleLevel --> "+ (s1 instanceof SingleLevel));//true
    System.out.println("s1 is oject of class java.lang.Object --> "+ (s1 instanceof java.lang.Object)); //true
    
    
    Class c1 = s1.getClass();
    System.out.println("\nCurrent class of s1 is --> "+c1);
    
    Class c2 = c1.getSuperclass();
    System.out.println("Super class of s1 is --> "+c2);
  }
}

Output:

single inheritance program

Multilevel inheritance:

  • Multilevel inheritance is the type of inheritance where a class behaves as a superclass as well as a subclass.
  • Thus Multilevel inheritance refers to a mechanism where one can inherit from a ‘derived class’, thereby making it a base class for the new class.

In the below image, you can see that C is a subclass of B and in turn, B is a subclass of A.

Multilevel inheritance:

Here is one example to show multi-level inheritance!

public class Person {
  
  public void methodPerson() {
    
    System.out.println("Class Person method");
  }	
}

public class Man extends Person{
      
    public void methodMan() {
      
      System.out.println("Class Man method");
    }	
}


public class Father extends Man {
  
  public void methodFather() {
    
    System.out.println("Class Father method");
  }
  
  public static void main(String[] args) {
    
    Father obj = new Father();
    obj.methodFather(); //calling current class method
    obj.methodMan(); //calling parent class method
    obj.methodPerson(); //calling grandparent class method		
  }

}

Output:

Multilevel inheritance: program

Hierarchical inheritance:

  • When more than one class is inherited from a single class, then it is known as Hierarchical inheritance.
  • Thus in this type of inheritance, a single class will have many child classes.

In the below image, Class B, C and D inherit the same class A.

Hierarchical inheritance:

 

Look at the programs below!

The parent class is Trees. It has 3 child classes namely CoconutTree, BananaTree and MangoTree.

public class Trees {
  
  public void methodTrees() {
    
    System.out.println("Method of Class Tree");
  }
}
public class CoconutTree extends Trees{
  
public void methodCoconutTree() {
    
    System.out.println("Method of Class CoconutTree");
  }

  public static void main(String[] args) {
  
    CoconutTree obj = new CoconutTree();
    obj.methodCoconutTree(); // calling current class method
    obj.methodTrees(); // calling parent class method
    
  }
}

public class BananaTree extends Trees {

public void methodBananaTree() {
    
    System.out.println("Method of Class BananaTree");
  }

  public static void main(String[] args) {
  
    BananaTree obj = new BananaTree();
    obj.methodBananaTree(); // calling current class method
    obj.methodTrees(); // calling parent class method
    
  }
}

public class MangoTree extends Trees {
  
  public void methodMangoTree() {
    
    System.out.println("Method of Class MangoTree");
  }

  public static void main(String[] args) {
  
    MangoTree obj = new MangoTree();
    obj.methodMangoTree(); // calling current class method
    obj.methodTrees(); // calling parent class method
    
  }
}

Multiple inheritance (through an interface ):

  • There are situations when a subclass seems to inherit from more than one parent class. For example, a Teaching Assistant is both a Student as well as a Teacher. Thus TeachingAssistant class inherits both Student class as well as Teacher class.
  • Thus, multiple inheritance refers to the concept of one class extending or inheriting more than 1 base class.
  • The problem with multiple inheritance is that the child class will have to manage the dependency on two base classes.

In the below image, you can see that C is a subclass of both A and B.

multiple inheritance

  • Classes never support multiple inheritance in Java due to “ambiguity”. However, it can be achieved by an interface.multiple inheritance ambiguity

 

 

Here’s how multiple inheritance is created in Java through an interface ! Make the parent classes an interface!

Creating a subclass from more than one parent class:

  • Interfaces always contain an abstract method. An abstract method does not have a body.
  • This abstract method of the parent class has to be overridden within the subclass.
  • In the below program, the method msg() is over-ridden within method msg() of C.
  • The object of a subclass always searches the member within the same class. So, it never creates any ambiguity.
public interface A {
  
  void msg();

}

public interface B {

  void msg();
}

public class C implements A, B {
  
  public void msg() {
    System.out.println("Hello");
  }
  
  public static void main(String[] args) {
    C obj = new C();
    obj.msg();
  }
}

Output:

interface example

Here is another example!

public interface Teacher {

  void subjectSpecification();
}

public interface Student {
  
  void calculateMarks();

}
import java.util.*;

public class AssistantTeacher implements Student, Teacher {
  
  public void subjectSpecification() {
    System.out.println("Enter the subject specification"
        + "");
    Scanner sc = new Scanner(System.in);
        String subject = sc.nextLine();
       	System.out.println("Subject specification: " + subject);
  }
  
  public void calculateMarks() {
    System.out.println("\nEnter the marks");
    Scanner sc = new Scanner(System.in);
        int mark1 = sc.nextInt();
        int mark2 = sc.nextInt();
        int result = mark1 + mark2;  
    System.out.println("Total marks: " + result);
  }
  
  public static void main(String[] args) {
    
    AssistantTeacher obj = new AssistantTeacher();
    obj.subjectSpecification();
    obj.calculateMarks();
    
  }
}

Output:

interface example teacher student

Hybrid inheritance:

  • In simple words, you can say that hybrid inheritance is a combination of single and multiple inheritances.
  • By using the concept of the interface, you can have multiple as well as a hybrid inheritance in Java.

In the below image, you can see that B and C are subclasses of A and in turn, S is a subclass of both B and C.

hybrid inheritance

 

In my next article, I will discuss Polymorphism and its implementation in Java.