Define a Drawable interface and make an abstract Shape implement both Drawable and Comparable<Shape> (by area); sort Circle and Rectangle objects and draw the two largest.
Solution
Main.java
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
interface Drawable { String draw(); }
abstract class Shape implements Drawable, Comparable<Shape> {
abstract double area();
public int compareTo(Shape o) { return Double.compare(area(), o.area()); }
}
class Circle extends Shape {
private final double r;
Circle(double r) { this.r = r; }
double area() { return Math.PI * r * r; }
public String draw() { return String.format("Circle(r=%.1f, area=%.1f)", r, area()); }
}
class Rect extends Shape {
private final double w, h;
Rect(double w, double h) { this.w = w; this.h = h; }
double area() { return w * h; }
public String draw() { return String.format("Rect(%.0fx%.0f, area=%.1f)", w, h, area()); }
}
public class Main {
public static void main(String[] args) {
List<Shape> shapes = new ArrayList<>(List.of(new Circle(2), new Rect(3, 5), new Circle(3), new Rect(2, 2)));
Collections.sort(shapes, Collections.reverseOrder());
for (Drawable d : shapes.subList(0, 2)) System.out.println(d.draw());
System.out.println("smallest: " + Collections.min(shapes).draw());
}
}
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!