Inheritance in Java

Introduction to Inheritance in Java

Inheritance in Java is a mechanism in object-oriented programming (OOP) that allows you to create new classes based on existing classes. The existing class is known as the **parent class** or **superclass**, and the new class is known as the **child class** or **subclass**.

Inheritance allows you to reuse the code and behavior of the parent class in the child class. This can save you time and effort when writing your code, and it can also make your code more readable and maintainable.

Types of inheritance in Java

Java supports the following four types of inheritance:

  • Single inheritance: This is the most common type of inheritance, where a child class can inherit from only one parent class.
  • Multilevel inheritance: This type of inheritance allows a child class to inherit from a parent class that has already inherited from another parent class.
  • Hierarchical inheritance: This type of inheritance allows multiple child classes to inherit from the same parent class.
  • Multiple inheritance: This type of inheritance allows a child class to inherit from multiple parent classes. However, multiple inheritance is not supported directly in Java. It can be achieved indirectly using interfaces.

Benefits of using inheritance in Java

There are several benefits to using inheritance in Java, including:

  • Code reuse: Inheritance allows you to reuse the code and behavior of the parent class in the child class. This can save you time and effort when writing your code.
  • Readability and maintainability: Inheritance can make your code more readable and maintainable by making it clear what code is inherited from the parent class and what code is new in the child class.
  • Polymorphism: Inheritance allows you to implement polymorphism, which is the ability of objects of different types to respond to the same method in different ways.

Example of inheritance in Java

The following example shows how to use single inheritance in Java:

// Parent class
class Animal {
  public void eat() {
    System.out.println("The animal is eating.");
  }
}

// Child class
class Dog extends Animal {
  @Override
  public void eat() {
    System.out.println("The dog is eating.");
  }
}

// Usage
public class Main {
  public static void main(String[] args) {
    Dog dog = new Dog();
    dog.eat(); // Prints "The dog is eating."
  }
}

In this example, the `Dog` class inherits from the `Animal` class. This means that the `Dog` class has access to all of the public methods and fields of the `Animal` class. The `Dog` class also overrides the `eat()` method to provide its own implementation.

Inheritance is a powerful feature of Java that can help you write more robust and efficient code. If you are working with Java, I encourage you to learn more about inheritance and how to use it in your code.

Protected Access Modifier in Java:


The protected access modifier in Java is used to control the visibility of classes, methods, and fields within a package and its subclasses. This means that the protected members of a class can be accessed by:

  • Classes in the same package: Classes within the same package as the class containing the protected member can directly access it.
  • Subclasses in other packages: Subclasses that inherit from the class containing the protected member can access it, even if they are in a different package.
  • Methods and constructors of the same class: Methods and constructors within the same class can also access protected members.

Key Points

  • Protected members are not accessible outside their package unless they are inherited by a subclass in another package.
  • Protected members are more accessible than private members, but less accessible than public members.
  • Using the protected access modifier can be useful for creating reusable code that can be extended and modified by other developers.

In the example given below, the protectedField and protectedMethod members of the BaseClass can be accessed by the SubClass even though they are in different packages.

package mypackage;

  public class BaseClass {
      protected int protectedField;
  
      protected void protectedMethod() {
          System.out.println("Protected method called");
      }
  }
  
  class SubClass extends BaseClass {
      public void accessProtectedMembers() {
          System.out.println("Accessing protected field: " + protectedField);
          protectedMethod();
      }
  }

  

Protected Access Modifier Matrix in Java

Access Modifier Within the same package Subclasses in other packages Outside the package
protected Yes Yes No

Explanation for the Matrix given above:

  • Within the same package: Classes within the same package can directly access protected members.
  • Subclasses in other packages: Subclasses that inherit from the class containing the protected member can access it, even if they are in a different package.
  • Outside the package: Classes that are not in the same package and do not inherit from the class containing the protected member cannot access it.

Behaviour of static varibles and Methods in Inheritance

Can a subclass inherit static variables from superclass in Java?

Yes, a subclass can inherit static variables from its superclass in Java.Static variables are class-level variables, meaning they belong to the class itself rather than to individual instances of the class. When a subclass inherits from a superclass, it inherits all of the public and protected static members of the superclass. Here is an example


class ParentClass {
    static int staticVariable = 10;
}

class ChildClass extends ParentClass {
    // ChildClass inherits the staticVariable from ParentClass
}

public class Main {
    public static void main(String[] args) {
        System.out.println(ChildClass.staticVariable); // Output: 10
    }
}

Can a subclass inherit static methods from superclass in Java?

Yes, a subclass in Java can inherit static methods from its superclass. Static methods are class-level methods, meaning they belong to the class itself rather than to individual instances of the class. When a subclass inherits from a superclass, it inherits all of the public and protected static members of the superclass.Here is an example

class ParentClass {
  static void staticMethod() {
      System.out.println("Static method from ParentClass");
  }
}

class ChildClass extends ParentClass {
  // ChildClass inherits the staticMethod from ParentClass
}

public class Main {
  public static void main(String[] args) {
      ChildClass.staticMethod(); // Output: Static method from ParentClass
  }
}

Exercises

Single Level Inheritance : A subclass inherits from only one superclass in Single Level Inheritance. The code below gives is an example for single level inheritance. The student class inherits from the person class. The data members and methods of the person class are reused by the student class.


package bbsProject;

public class BbsDemo {

    public static void main(String[] args) {
        Student student = new Student();
        student.displayDetails();
        student.displayRegNo();
    }
}

class Person { //super class
    protected String name;
    protected String address;

    protected void displayDetails() {
        System.out.println("Name: " + this.name + "\nAddress: " + this.address);
    }
}

class Student extends Person { //sub class

    protected String regNo;

    public Student() {
        this.name = "Satish";
        this.address = "Vellore";
        this.regNo = "12BCE";
    }

    protected void displayRegNo() {
        System.out.println("Registration Number: " + this.regNo);
    }
}

Output
Name: Satish
Address: Vellore
Registration Number: 12BCE
  

Multilevel inheritance is a type of inheritance where a class (subclass) inherits from another subclass, which in turn inherits from a superclass, forming a hierarchical structure. This allows for a more complex and flexible inheritance relationship. The code below demonstrates multi level inheritance in Java. The class ResearchScholar is specific type of student. It inherits the methods and attributes of the Student class. The Student class inturn inherits from the person class.


  package bbsProject;
  public class bbsdemo
  {
      public static void main(String[] args) {
           ResearchScholar Scholar = new ResearchScholar();
           Scholar.displayDetails();
           Scholar.displayRegNo();
           Scholar.displayCubicleNo();
        }
    }
  
    class Person {
        protected String name;
        protected String address;
  
        protected void displayDetails() {
            System.out.println("Name: " + this.name + "\nAddress: " + this.address);
        }
    }
  
    class Student extends Person {
  
        protected String regNo;
  
        public Student() {
            this.name = "Satish";
            this.address = "Vellore";
            this.regNo = "12BCE";
        }
  
        protected void displayRegNo() {
            System.out.println("Registration Number: " + this.regNo);
        }
    }
    
    class ResearchScholar extends Student
    {
      String cubicleNo;
      
      public ResearchScholar() {
        this.cubicleNo="116";
      }
      
      protected void displayCubicleNo()
      {
         System.out.println("Cubicle Number: " + this.regNo);
      }
    }
Output
Name: Satish
Address: Vellore
Registration Number: 12BCE
Cubicle Number: 12BCE
  

Hierarchical inheritance in Java is a type of inheritance where multiple subclasses inherit from a single superclass. This creates a hierarchical structure, where the superclass is at the top and the subclasses are at the bottom. Here the Person Class is inherited by Student Class and Faculty Class.


  package javaProgrammingDemo;

public class JavaLabClass {

    public static void main(String[] args) {
        Student ram = new Student("Ram", "Pune", "12322", "12BCE");
        ram.login("test", "test");
        ram.displayStudentDetails();

        Faculty satish = new Faculty("Satish", "Vellore", "23333", "111", "564");
        satish.login("test", "test");
        satish.displayFacultyDetails();
    }
}

class Person {
    protected String name; 
    protected String address; 
    protected String phoneNumber; 

    public Person(String name, String address, String phoneNumber) {
        this.name = name;
        this.address = address;
        this.phoneNumber = phoneNumber;
    }

    public  
 void login(String username, String password) {
        if (username.equals("test") && password.equals("test")) {
            System.out.println("Valid User");
        } else {
            System.out.println("Check your username and password");
        }
    }
}

class Student extends Person {
    protected String regno; 

    public Student(String name, String address, String phoneNumber, String regno) {
        super(name, address, phoneNumber);
        this.regno = regno;
    }

    public void displayStudentDetails() {
        System.out.println(this.name + this.address + this.phoneNumber + this.regno);
    }
}

class Faculty extends Person {
    protected String employeeId;
    protected String cabinNumber; 

    public Faculty(String name, String address, String phoneNumber, String employeeId, String cabinNumber) {
        super(name, address, phoneNumber);
        this.employeeId = employeeId;
        this.cabinNumber = cabinNumber;
    }

    public void displayFacultyDetails() {
        System.out.println(this.name + this.address + this.phoneNumber + this.employeeId + this.cabinNumber);
    }
}  

Output
Valid User
RamPune1232212BCE
Valid User
SatishVellore23333111564