Inheritance is one of the most important features of Java. With Inheritance you can extend the features defined in one class into another Class. Thus promoting code reusability. The Class which one extends into new Class is Called Super Class and the extending class is called Sub Class. The following template shows basic keywords of achieving Inheritance in Java.

class B extends class A {
}

The above code includes a Java reserved keyword extends which is used to extend a Class into another. Class B is extending Class A which means that all the data members and methods which are defined in class A are now part of class B.

Let's consider a real world example of Inheritance.

public class Box {
    
    int height;
    int width;
    int length;
    
    public Box(){
        this.height = -1;
        this.width = -1;
        this.length = -1;
    }
    
    public Box(int height, int width, int length) {
        this.height = height;
        this.width = width;
        this.length = length;
    }
    
    public double calculateVolume(){
        return height*width*length;
    }

}

Let's suppose you have a Box class with simple parameters of height, weight and length and a method that returns the Volume of the Box. Now you want to extend this class to include the weight parameter as well. You can do this as below.

public class BoxWeight extends Box {

    int weight;

    public BoxWeight(int height, int width, int length, int weight) {
        this.height = height;
        this.width = width;
        this.length = length;
        this.weight = weight;
    }

    public void printWeight(){
        System.out.println("Weight is "+weight);
    }

}

class BoxWeight extends the Box class, and with this inheritance all the variables that are defined in Box class becomes part of BoxWeight, Consider the below main class to see both Classes in action.

public class Main {

    public static void main(String args[]) {
        BoxWeight boxWeight = new BoxWeight(10, 15, 20, 400);
        System.out.println(boxWeight.calculateVolume());
        boxWeight.printWeight();

    }

}

Output will be

3000.0
Weight is 400

As you can notice BoxWeight class can now access member methods of Box Class as well. But we are able to set the height,width and length of Box class from BoxWeight because they are defined public in the SuperClass i.e. Box. What if the member methods of Box class are defined private? Let's Look at super keyword in Java to learn how we will handle that situation. Super Keyword in Java.

Comments