[英]An advice for a design between parent and child classes?
我正在進行物理模擬。
我有一個ArrayList
,它包含我的模擬中的所有對象。 我有一個父類: Shape
和兩個子類: Circle
和Rectangle
。
當然,父類沒有draw()
方法,但每個子類都有。 因此,當我循環遍歷列表以繪制每個元素時,它不允許我,因為Shape
類中沒有draw()
方法(因為我將列表定義為ArrayList<Shape>
,並且使用子類實例添加每個新元素)。
有沒有辦法以一種良好而整潔的方式解決這個問題?
它似乎為Shape
類提供了一個抽象方法,其中所有子類共享一個共同的行為最適合手頭的任務。
考慮這是Shape
類:
public abstract class Shapes{
public abstract void Draw();
}
Rectangle
類:
public class Rectangle extends Shapes{
public void Draw(){
System.out.println("Rectangle");
}
}
Circle
類:
public class Circle extends Shapes{
public void Draw(){
System.out.println("Circle");
}
}
現在考慮到Circle
和Rectangle
都是Shape
類型,你可以創建Circle
或/和Rectangle
類型的對象,將它們添加到ArrayList,迭代它,並在每個對象上調用Draw()
方法,如下所示:
ArrayList<Shapes> shapes = new ArrayList<>();
shapes.add(new Circle());
shapes.add(new Rectangle());
shapes.forEach(Shapes::Draw);
在每個對象上調用Draw()
方法時的結果:
Circle
Rectangle
前進的最好方法是使用接口。
public interface Shape {
void draw();
}
public class Rectangle implements Shape {
@Override
public void draw() { // draw rect }
}
public class Circle implements Shape {
@Override
public void draw() { // draw circle }
}
如果你希望Shape與它的子項共享一些其他邏輯,你可以使用任何其他代碼創建一個實現Shape的AbstractShape類,並使用這個抽象類擴展子類。
我就是這樣做的。
名為Shapes的類具有List < Shape > Shape的字段,該類是包含方法draw()getArea()或其他任何方法的接口。 有盡可能多的類實現Shape ,circle,rectangle,square等。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.