Search⌘ K

Solution Review: Implement and Override Method

Explore how to implement and override methods in Java within the polymorphism chapter. Learn to customize behavior like area calculation by overriding methods, improving your code’s modularity and flexibility.

We'll cover the following...

Solution

Java
// Base Class
class Shape {
// Private Data Members
private double area;
public Shape() { // Default Constructor
area = 0;
}
// Getter Function
public double getArea() {
return area;
}
}
// Derived Class
class Circle extends Shape {
private double radius;
public Circle(double radius) { // Constructor
this.radius = radius;
}
// Overridden Method the getArea() which returns the area of Circle
public double getArea() {
return (radius*radius) * 3.14;
}
}
class Demo {
public static void main(String args[]) {
Shape circle = new Circle(2);
System.out.println(circle.getArea());
}
}

Explanation

The solution is very simple.

  • Line 29 - 31: The getArea() method is overridden in the Circle class to calculate the area of the circle.
  • The area is calculated using the conventional formula:

...