2017-09-15 98 views
-1

我有一个赋值,可以计算形状的面积和周长。返回子类的子类

超类:

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类:

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类:

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类。这就是我想要的。

+0

你试了一下自己? – nullpointer

+0

你在说什么?我已经尝试过了。 –

+0

@tima哈哈新手在这里 –

回答

0

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