...

/

Solution Review: Implement and Override Method

Solution Review: Implement and Override Method

This review provides a detailed analysis to solve the 'Implement and Override the Method in the Derived Class' challenge.

We'll cover the following...

Solution

Press + to interact
// 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:

...