Java

Inheritance In Java

One of the helpful features of OOPs is inheritance. It enables one class to use the attributes and functions of another. In Java, inheritance is used to allow for code reuse, requiring only the unique features to be written for a class; the other common attributes and capabilities may be inherited from another class.

Only when a class extends another class are its fields and methods inheritable. Class A extends class B in the following snippet, for instance. The fields and methods of class B are now accessible to class A.

class A extends B
{
}

Let’s examine the inheritance principle of parent and child classes:

Child Class: A child class, subclass, or derived class is a class that adds characteristics to another class. Class A is the child class in the aforementioned code.

Parent Class: The parent class, super class, or base class is the one that shares fields and methods with the child class. Class B is the parent class in the aforementioned code.

Advantages of Inheritance

  • The code becomes less redundant because to inheritance. The fields and methods of a parent class may be used by a child class. There is no need to recreate the same redundant code.
  • The ability to reuse code thanks to inheritance makes your Java program more reusable.
  • code size is minimized The amount of lines of code is decreased by deleting unnecessary lines.
  • Enhances the logical structure of the code, making it easier for programmers to see the connections between various classes.

Syntax: Inheritance in Java

The extends keyword is used to inherit a class. In this case, class ABC is the parent class and class XYZ is the kid class. The methods and attributes of the class ABC are inherited by the class XYZ.

class XYZ extends ABC
{
}

Terminologies used in Inheritance:Let’s go through the terminology used in this tutorial so there is no misunderstanding.

  • Parent class is synonymous with base class and super class.
  • Child class is synonymous with sub class and derived class.
  • Data members are synonymous with properties and fields.
  • Method is a synonym for functionality.

Inheritance Example in Java

We have a base class called Teacher and a subclass called PhysicsTeacher in this example. The following properties and methods from the parent class are inherited by the child class:

  • Properties: designation and collegeName properties
  • Method: does()

Child classes like MathTeacher, MusicTeacher, and PhysicsTeacher may access these attributes and methods directly from the base class without having to create any additional code.

class Teacher {
  //fields of parent class
  String designation = "Teacher";
  String collegeName = "Beginnersbook";

  //method of parent class
  void does(){
    System.out.println("Teaching");
  }
}

public class PhysicsTeacher extends Teacher{
  //field of child class
  String mainSubject = "Physics";
  public static void main(String args[]){
    PhysicsTeacher obj = new PhysicsTeacher();
    //accessing the fields of parent class
    System.out.println(obj.collegeName);
    System.out.println(obj.designation);

    System.out.println(obj.mainSubject);

    //accessing the method of parent class
    obj.does();
  }
}

Output:

Beginnersbook
Teacher
Physics
Teaching

Java Inheritance instanceof keyword

If an object is a member of the class or a member of its parent class, the instanceof keyword returns true.

class A{
}
class B extends A{
}
public class JavaExample extends B{
  public static void main(String args[]) {
    A obj1 = new A();
    B obj2 = new B();
    JavaExample obj3 = new JavaExample();
    System.out.println(obj1 instanceof A);
    System.out.println(obj2 instanceof A);
    System.out.println(obj1 instanceof B);
    System.out.println(obj3 instanceof B);
  }
}

Output:

true
true
false
true

Types of inheritance in Java

In Java, there are four types of inheritance:

  • Single
  • Multilevel
  • Hierarchical
  • Hybrid

Single Inheritance

A single child class inherits the methods and attributes of a single parent class under single inheritance. Class A is the parent class in the following diagram, while class B is the child class.

Multilevel Inheritance

A parent class becomes the child class of another class when there are many levels of inheritance. Class B is a parent class of class C in the figure below, but it is also a child class of class A. There is a notion of an intermediate class in this form of inheritance; in this case, class B serves as an intermediate class.

Hierarchical Inheritance

Numerous classes extend the same class under hierarchical inheritance. Classes B, C, and D all expand class A, as indicated in the figure below.

Hybrid Inheritance

Hybrid inheritance is the combination of several inheritance types in a single program. For instance, if class A is extended by classes B and C, and class D is extended by class C, this is an example of a hybrid inheritance since it combines single inheritance with hierarchical inheritance.

Multiple Inheritance

It alludes to the idea that one class may extend several classes, i.e., a child class can have more parent classes. For instance, both classes A and B are extended by class C. You may learn more about Java’s lack of support for multiple inheritance here.

Inheritance Access Specifier in Java

Only the data members and methods of the parent class that are defined as public or protected may be inherited by the derived class.

The derived class cannot access the members or methods of the super class if they are marked as private. Only the class it belongs to may access the private members. As seen in the following example, such private members can only be accessed via public or protected getter and setter methods of the super class.

class Teacher {
  private String designation = "Teacher";
  private String collegeName = "Beginnersbook";
  public String getDesignation() {
    return designation;
  }
  protected void setDesignation(String designation) {
    this.designation = designation;
  }
  protected String getCollegeName() {
    return collegeName;
  }
  protected void setCollegeName(String collegeName) {
    this.collegeName = collegeName;
  }
  void does(){
    System.out.println("Teaching");
  }
}

public class JavaExample extends Teacher{
  String mainSubject = "Physics";
  public static void main(String args[]){
    JavaExample obj = new JavaExample();
    /* Note: we are not accessing the data members
     * directly we are using public getter method
     * to access the private members of parent class
     */
    System.out.println(obj.getCollegeName());
    System.out.println(obj.getDesignation());
    System.out.println(obj.mainSubject);
    obj.does();
  }
}

The output is:

Beginnersbook
Teacher
Physics
Teaching

In the example above, it’s crucial to keep in mind that the child class may access the secret members of the parent class using protected methods.

Instance variables (data members) and methods are only available inside the parent class and its child classes when we make them protected. These access specifiers—public, protected, private, etc.—have all been covered here: Java’s access specifier.

How to use constructor in inheritance in java

When we create an object of a subclass, the constructor of the subclass is called by default, which calls the constructor of the superclass. As a result, in inheritance, things are built from the top down.

The super keyword may be used to explicitly invoke the constructor for the superclass, however this line should come first in the constructor. The super keyword designates the class in the hierarchy that comes before the calling class. It is not allowed to reach an ancestor class other than the immediate parent using multiple super keywords.

class ParentClass{
  //Parent class constructor
  ParentClass(){
    System.out.println("Constructor of Parent");
  }
}
class JavaExample extends ParentClass{
  JavaExample(){
    /* It by default invokes the constructor of parent class
     * You can use super() to call the constructor of parent.
     * It should be the first statement in the child class
     * constructor, you can also call the parameterized constructor
     * of parent class by using super like this: super(10), now
     * this will invoke the parameterized constructor of int arg
     */
    System.out.println("Constructor of Child");
  }
  public static void main(String args[]){
    //Creating the object of child class
    new JavaExample();
  }
}

Output:

Constructor of Parent
Constructor of Child

Inheritance and Method Overriding

Method overriding is the act of declaring a method in a child class that is already existent in the parent class. In this situation, the method’s child class version is called when it is called from an object of the child class. However, we may use the super keyword to invoke the parent class function, which is done as follows:

class ParentClass{
   //Parent class constructor
   ParentClass(){
	System.out.println("Constructor of Parent");
   }
   void disp(){
	System.out.println("Parent Method");
   }
}
class JavaExample extends ParentClass{
   JavaExample(){
	System.out.println("Constructor of Child");
   }
   void disp(){
	System.out.println("Child Method");
        //Calling the disp() method of parent class
	super.disp();
   }
   public static void main(String args[]){
	//Creating the object of child class
	JavaExample obj = new JavaExample();
	obj.disp();
   }
}

The output is :

Constructor of Parent
Constructor of Child
Child Method
Parent Method

 

 

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button