Welcome to Kodo
Create a free account to practice coding problems from your slides.
OR
By continuing you agree to the terms and privacy policy.
Inheritance & Polymorphism
Problem
Shape Hierarchy
Build a small shape hierarchy that uses polymorphism through an abstract base class.
- Define
Shapeas abstract with one abstract method,area(). Circle(radius)overridesarea()to returnπ × r².Rectangle(width, height)overridesarea()to returnw × h.
A Shape reference holds either subclass; the right area() runs at call time.
Test Cases
- ✓new Circle(5).area()→78.5398
- ✓new Rectangle(3, 4).area()→12.0
- ✓new Circle(2).area()→12.5663
Shape.java
1abstract class Shape {
2abstract double area();
3}
4
5class Circle extends Shape {
6double radius;
7Circle(double r) {
8radius = r;
9}
10@Override
11double area() {
12return Math.PI * radius * radius;
13}
14}
15
16class Rectangle extends Shape {
17double width, height;
Run
Submit