0

我有一个抽象类 Shape、一些子类和一些方法来计算面积、周长和绘制被覆盖的形状。我试图在这个应用程序的抽象类中找到一个模板方法,但我想不出任何方法。我还没有找到任何通用方法,它们对于所有形状都是相同的,并且也会在 GUI 上产生一些东西。我想在抽象类中有一个方法来比较两个形状的区域,但我无法理解如何做到这一点,因为我认为我不能使用它(指类的实例)一个抽象类。所有形状有什么共同点吗?我的模板方法是什么?谢谢你。

4

2 回答 2

0

这是您compareArea()的模板方法:

public class Test {
public static void main(String[] args) {
    Shape rec = new Rectangle();
    Shape sqr = new Square();
    int diff = rec.compareArea(sqr);
    System.out.println(diff);
 }
}

abstract class Shape{
public int compareArea(Shape otherShape){
    return computeArea() - otherShape.computeArea();
 }
abstract int computeArea();
}
class Square extends Shape{
int s = 2;
@Override
int computeArea() {
    return s * s;
 }
}
class Rectangle extends Shape{
int l = 3;
int b = 4;
@Override
int computeArea() {
    return l * b;
 }
}
于 2012-12-24T07:58:33.233 回答
0

当然你可以做 areaEquals:

public abstract class Shape {
    public boolean areaEquals(Shape otherShape) {
        return this.area() == otherShape.area();
    }

    public abstract double area();
}

整个想法是面积计算是特定于每个形状的,但比较对于所有可以计算自己面积的形状都是通用的。

于 2012-12-24T07:48:20.723 回答