Search code examples
javainterfacecomparable

I need to compare two shapes to determine which one is bigger or smaller than the other using comparable interface


public abstract class Shape {
protected int height;
protected int width;


public Shape(int height, int width) {
this.height = height;
this.width = width;

}




public final void printArea() {
System.out.println("This " + getName() + " has a height of " +
height + ", a width of " + width + ", and an area of " + 
getArea() + ".");
}



public final void printPerimeter() {
System.out.println("This " + getName() + " has a height of " +
height + ", a width of " + width + ", and a perimeter of " + 
getPerimeter() + ".");
}



protected abstract String getName();
protected abstract double getArea();
protected abstract double getPerimeter();

}
}

This is my starting code I have three other classes Rectangle, RightTriangle, and Square all with code but im focusing on my shape class first I need to implement Comparable interface Comparable. Then because the get area method is overridden in each child class. I can write a single compareTo() method in the Shape class that will work correctly when comparing any type of Shape or subclass object to any other. I need to Implement the compareTo() method. So public int compareTo(Shape s) correct? Now the code for the comparison is int k = getName().compareTo(s.getName()); . I need to Override the toString() method inherited from Object in the Shape class and have it return a String that includes the name of the current object and its area in the following format:

name: area

I am just needing some guidance


Solution

  • int compareTo(Shape shape) {
       return getArea() - shape.getArea();
    }
    

    this will allow you to compare shapes and the method will return <0 if it smaller, 0 if equal and positive number if it has a bigger are just like Comparable interface is supposed to do