LearnFrenzy
Sign in Take a free test

Interfaces · Interfaces Programs · Question 5

Shapes that are both Comparable and Drawable in Java Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 5 Back to Exercise

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());
    }
}

Output Verified by compiling and running

Circle(r=3.0, area=28.3)
Rect(3x5, area=15.0)
smallest: Rect(2x2, area=4.0)

Every Shape is a Drawable and a Comparable, so the same objects can be sorted, compared and drawn.

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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links