Implementation
Turn the design into working code: define the base class, implement concrete shapes, and print results from a mixed list.
Plan recap
We will code the base Shape with area() and perimeter(), then add Circle and Rectangle. Keep names short and math readable, and prefer small helper methods for printing.
Code: base + Circle
Base class defines the API and a small info() helper. Circle implements the math and toString() for clear output.
public class Main {
// Base class with a tiny print helper
static abstract class Shape {
abstract double area();
abstract double perimeter();
String info() {
return String.format("area=%.2f, per=%.2f", area(), perimeter());
}
}
static class Circle extends Shape {
double radius;
Circle(double r) {
// simple guard to avoid negative sizes for beginners
radius = (r < 0) ? 0 : r;
}
double area() { return Math.PI * radius * radius; }
double perimeter() { return 2 * Math.PI * radius; }
public String toString() { return "Circle " + info(); }
}
public static void main(String[] args) {
Shape s = new Circle(2.5);
System.out.println(s); // prints Circle area/perimeter
}
}
All lessons in this course
- Design
- Implementation
- Polymorphic Behaviors