w3resource

Java Inheritance Programming - Create a class called Shape with a method called getArea and a subclass called Rectangle

Java Inheritance: Exercise-3 with Solution

Write a Java program to create a class called Shape with a method called getArea(). Create a subclass called Rectangle that overrides the getArea() method to calculate the area of a rectangle.

Sample Solution:

Java Code:

// Shape.java
// Parent class Shape
public class Shape {
    public double getArea() {
        return 0.0;
    }
} 

// Rectangle.java
// Child class Rectangle
public class Rectangle extends Shape {
    private double length;
    private double width;
    
    public Rectangle(double length, double width) {
        this.length = length;
        this.width = width;
    }
  @Override
    public double getArea() {
        return length * width;
    }
}
// Main.java
// Main class
public class Main {
    public static void main(String[] args) {
    Rectangle rectangle = new Rectangle(3.0, 10.0);
    double area = rectangle.getArea();
    System.out.println("The area of the rectangle is: " + area);
    }
}

Sample Output:

The area of the rectangle is: 30.0

Explanation:

In the above exercise, the Shape class has a single method called getArea() that returns a double value. The Rectangle class is a subclass of Shape and overrides the getArea() method to calculate the area of a rectangle using the formula length x width. The Rectangle class constructor sets length and width values.

Finally in the main() method we create an instance of the Rectangle class and call its getArea() method to get the rectangle's area.

Flowchart:

Flowchart: Create a class called Shape with a method called getArea and a subclass called Rectangle.
Flowchart: Create a class called Shape with a method called getArea and a subclass called Rectangle.
Flowchart: Create a class called Shape with a method called getArea and a subclass called Rectangle.

Java Code Editor:

Contribute your code and comments through Disqus.

Previous: Create a class called Vehicle with a method called drive(). Create a subclass called Car that overrides the drive() method to print "Repairing a car".
Next: Employee class with methods called work, getSalary.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.