-1

I have an assignment that calculates the area and perimeter of shapes.

The superclass:

public abstract class Shape implements Serializable {
    private static final long serialVersionUID = -1231855623100981927L;

    public abstract boolean draw();
    public abstract String area();
    public abstract String perimeter();
    public abstract String characteristic();
}

Rectangle class:

public class Rectangle extends Shape {

    private double x;
    private double y;

    public Rectangle() {}

    public Rectangle(double x, double y) {
        this.x = x;
        this.y = y;
    }
}

Square class:

public class Square extends Rectangle {

    private double x;

    public Square() {}

    public Square(double side) {       
        super(side, side);
        this.x = side;
    }

    public Square square(double side){
        this.x = side;
        return this;
    }
}

Main class:

 Shape rec = new Rectangle();

What I want is when the height and width of a rectangle are equal, it will return the Square class instead of the Rectangle class. That's all I want.

tima
  • 1,498
  • 4
  • 20
  • 28

1 Answers1

0

Once you have a Rectangle, you can't turn it into a Square or anything like that. You might use a factory. The factory would be an instance of a class with a method that, for your case, would take a width and a height. When they are equal, it will return a new Square(x) and when they are not equal, will return a new Rectangle(x, y). You'd need to move the System.in readLine calls to an application entry point (presumably a main method), and the factory method would be called from there.

Lucas Ross
  • 1,049
  • 8
  • 17