[英]Concrete method in super class-abstract class
我有一個抽象類Shape,一些子類和一些方法來計算面積,周長和繪制被覆蓋的形狀。 我正在嘗試在此應用程序的抽象類中找到一個模板方法,但我想不出任何方法。 我還沒有找到任何通用的方法,這些方法對於所有形狀都相同,也不會在GUI上產生任何東西。 我曾想過在抽象類中有一個方法來比較兩個形狀的面積,但是我不知道該怎么做,因為我認為我不能在其中使用它(指的是類的實例)抽象類。 所有形狀都有什么共同點嗎,我的模板方法可能是什么? 謝謝。
確定您可以做areaEquals:
public abstract class Shape {
public boolean areaEquals(Shape otherShape) {
return this.area() == otherShape.area();
}
public abstract double area();
}
整個想法是,面積計算是每種形狀所特有的,但是比較是所有可以計算自己面積的形狀所共有的。
這里您的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;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.