-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAbc.java
More file actions
28 lines (25 loc) · 940 Bytes
/
Copy pathAbc.java
File metadata and controls
28 lines (25 loc) · 940 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public sealed interface Shape permits Circle, Rectangle {}
final class Circle implements Shape {
final double radius;
Circle(double r) { this.radius = r; }
double area() { return Math.PI * radius * radius; }
public String toString() { return "Circle(r=" + radius + ")"; }
}
final class Rectangle implements Shape {
final double w, h;
Rectangle(double w, double h) { this.w = w; this.h = h; }
double area() { return w * h; }
public String toString() { return "Rectangle(" + w + "x" + h + ")"; }
}
public class Abc {
public static void main(String[] args) {
Shape[] shapes = { new Circle(2.0), new Rectangle(3, 4) };
for (Shape s : shapes) {
if (s instanceof Circle c) {
System.out.println(c + " area=" + c.area());
} else if (s instanceof Rectangle r) {
System.out.println(r + " area=" + r.area());
}
}
}
}