返回子类的子类

时间:2017-09-15 00:58:37

标签: java

我有一个计算形状面积和周长的作业。

超类:

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

矩形类:

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

主要课程:

 Shape rec = new Rectangle();

我想要的是当矩形的高度和宽度相等时,它将返回Square类而不是Rectangle类。这就是我想要的一切。

1 个答案:

答案 0 :(得分:0)

一旦你有一个矩形,你就不能把它变成一个正方形或类似的东西。您可以使用factory。工厂将是一个具有方法的类的实例,对于您的情况,该方法将采用宽度和高度。当它们相等时,它将返回new Square(x),当它们不相等时,将返回new Rectangle(x, y)。您需要将System.in readLine调用移动到应用程序入口点(可能是main方法),并且将从那里调用工厂方法。

相关问题