Java
Summary - Abstract class
Combine abstract methods and sealed to write a geometry hierarchy.
Summary: Geometry hierarchy
In this summary you'll design a geometry hierarchy. The Shape abstract class defines the area abstract method; Circle and Square implement this contract. You close the hierarchy with sealed.
First you'll define abstract class Shape { abstract double area(); }. Then Circle and Square subclasses override the area method. Finally you close the hierarchy with sealed class Shape permits Circle, Square. This structure combines abstract methods and sealed in a real scenario. Each subclass writes its own area calculation; but all follow the Shape contract.
Exercise Define the Shape abstract class and Circle
Define an abstract class Shape; add the abstract double area(); signature. Write class Circle extends Shape; add a double r field, a Circle(double r) constructor (assign the field) and a public double area() method whose body returns Math.PI * r * r;. In main create Circle c = new Circle(2); and run System.out.println(c.area());.
Show example solution
abstract class Shape {
abstract double area();
}
class Circle extends Shape {
double r;
Circle(double r) {
this.r = r;
}
public double area() {
return Math.PI * r * r;
}
}
class Main {
public static void main(String[] args) {
Circle c = new Circle(2);
System.out.println(c.area());
}
}
Exercise Close the hierarchy with sealed Shape
In this file you'll make Shape sealed and add the Circle and Square subclasses. Define sealed abstract class Shape permits Circle, Square; add abstract double area(); inside. Write final class Circle extends Shape; add double r, Circle(double r) and public double area() (body return Math.PI * r * r;). Write final class Square extends Shape; add double s, Square(double s) and public double area() (body return s * s;). In main print new Circle(2).area() and new Square(3).area() on separate lines.
Show example solution
sealed abstract class Shape permits Circle, Square {
abstract double area();
}
final class Circle extends Shape {
double r;
Circle(double r) {
this.r = r;
}
public double area() {
return Math.PI * r * r;
}
}
final class Square extends Shape {
double s;
Square(double s) {
this.s = s;
}
public double area() {
return s * s;
}
}
class Main {
public static void main(String[] args) {
System.out.println(new Circle(2).area());
System.out.println(new Square(3).area());
}
}
Test yourself
-
How should Shape be defined in the geometry hierarchy?
- interface
- record
- final class
- abstract class
Show answer
abstract class — Shape is an abstract class; subclasses inherit it.
-
Match the geometry hierarchy parts
- Shape
- Abstract base
- Circle
- Circle subclass
- area
- Abstract method
- sealed
- Closing keyword
-
Complete the abstract area signature
abstract class Shape {
____ double area();
}
Show answer
abstract class Shape {
abstract double area();
}
Next lesson: Polymorphism basics