In this article on How to Implement Inheritance in Java, I will demonstrate the concept of inheritance using a simple example of a Box class.
Problem Statement
Demonstrate how to create a class called Box with instance variables width, height, and depth. Create another class BoxWeight which inherits class Box with an additional instance variable weight. Compute the volume of the box using inheritance.
Solution
class Box {
// Instance variables
protected double width;
protected double height;
protected double depth;
// Constructor for Box class
public Box(double width, double height, double depth) {
this.width = width;
this.height = height;
this.depth = depth;
}
// Method to calculate and return the volume of the box
public double calculateVolume() {
return width * height * depth;
}
// Display box information
public void display() {
System.out.println("Box Dimensions:");
System.out.println("Width: " + width);
System.out.println("Height: " + height);
System.out.println("Depth: " + depth);
}
}
class BoxWeight extends Box {
// Additional instance variable
private double weight;
// Constructor for BoxWeight class
public BoxWeight(double width, double height, double depth, double weight) {
super(width, height, depth); // Call the constructor of the superclass
this.weight = weight;
}
// Display box information including weight
@Override
public void display() {
super.display(); // Call the display method of the superclass
System.out.println("Weight: " + weight);
}
}
public class BoxInheritanceDemo {
public static void main(String[] args) {
// Create an object of BoxWeight
BoxWeight boxWithWeight = new BoxWeight(5.0, 3.0, 2.0, 10.0);
// Display box dimensions and weight
boxWithWeight.display();
// Calculate and display the volume
double volume = boxWithWeight.calculateVolume();
System.out.println("Volume of the box: " + volume);
}
}
In this program:
- We have a
Box
class with instance variableswidth
,height
, anddepth
, along with a method to calculate the volume of the box and adisplay
method to print box dimensions. - The
BoxWeight
class inherits from theBox
class and adds an additional instance variableweight
. It also overrides thedisplay
method to include the weight information. - In the
main
method, we create an object ofBoxWeight
with dimensions and weight. - Then, we call the
display
method of theBoxWeight
class, which displays both dimensions and weight. - Filally, we calculate and display the volume of the box using the inherited
calculateVolume
method from theBox
class.
This program showcases the concept of inheritance and also adds a unique feature by overriding the display
method in the subclass to include the weight information.
Further Reading
Spring Framework Practice Problems and Their Solutions
From Google to the World: The Story of Go Programming Language
Why Go? Understanding the Advantages of this Emerging Language
Creating and Executing Simple Programs in Go