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 Classclass Shape {// Private Data Membersprivate double area;public Shape() { // Default Constructorarea = 0;}// Getter Functionpublic double getArea() {return area;}}// Derived Classclass Circle extends Shape {private double radius;public Circle(double radius) { // Constructorthis.radius = radius;}// Overridden Method the getArea() which returns the area of Circlepublic 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 theCircle
class to calculate the area of the circle.
- The area is calculated using the conventional formula:
...