Java Inheritance Programming - Java Program to Demonstrate Method Overriding with Shape and Rectangle
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:
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:
For more Practice: Solve these Related Problems:
- Write a Java program where the "Rectangle" subclass checks if the shape is a square.
- Write a Java program where the "Shape" class has an attribute for color, and subclasses modify the color dynamically.
- Write a Java program where the "Rectangle" subclass adds a method to resize the shape.
- Write a Java program where the "Shape" class includes a method to determine if the shape is 2D or 3D.
Go to:
Java Code Editor:
Contribute your code and comments through Disqus.
PREV : 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?