嗨,有人可以演示如何使用不同的物件型別填充型別參考和陣列。
我已經為相應的物件創建了類(三角形,圓形,矩形),但我無法找到一種方法讓這些類的每個物件填充陣列的每個索引
我是 Java 新手,一直被困在作業上。
分配問題: 用可以是以下任何型別的物件隨機填充此陣列:三角形、圓形和矩形。每個物件的狀態(例如,位置或半徑等)也是隨機分配的
uj5u.com熱心網友回復:
您可以通過幾種方式實作它。第一個是將不同的物件放入原始Object型別的集合中。對于這種情況,您不需要實作任何介面,但需要在從串列中檢索時將物件強制轉換為您想要的型別。雖然這種方法很簡單并且可以使用幾次,但不推薦使用。
另一種方法是,如果您為所有類實作一個通用的 Shape 介面,然后創建一個 Shape 串列。然后,您可以將所有形狀放入該集合中。您還可以在從串列中檢索時呼叫可以在界面上定義的通用形狀方法。您還可以創建Shape一個Abstract類或一個常規類并將其用作一個Super類并從Shape
public class Triangle implements Shape {
}
public class Circle implements Shape {
}
public class Rectangle implements Shape {
}
public interface Shape {
}
public static void main(String... args) {
Triangle t = new Triangle();
Circle c = new Circle();
Rectangle r = new Rectangle();
// Raw Type
List<Object> shapeListRaw = new ArrayList<>();
shapeListRaw.add(t);
shapeListRaw.add(c);
shapeListRaw.add(r);
// Strictly Typed
List<Shape> shapeListTyped = new ArrayList<>();
shapeListTyped.add(t);
shapeListTyped.add(c);
shapeListTyped.add(r);
//Similarly Raw type array
Object[] shapeArrRaw = new Object[3];
shapeArrRaw[0] = t;
shapeArrRaw[1] = c;
shapeArrRaw[2] = r;
//Typed Array
Shape[] shapeArrTyped = new Shape[3];
shapeArrTyped[0] = t;
shapeArrTyped[1] = c;
shapeArrTyped[2] = r;
}
uj5u.com熱心網友回復:
您可以使用工廠模式。
訪問https://www.tutorialspoint.com/design_pattern/factory_pattern.htm
public class ShapeFactory {
//use getShape method to get object of type shape
public Shape getShape(String shapeType){
if(shapeType == null){
return null;
}
if(shapeType.equalsIgnoreCase("CIRCLE")){
Circle c = new Circle();
c.setRadius(Math.random()*100);
return c;
} else if(shapeType.equalsIgnoreCase("RECTANGLE")){
return new Rectangle();
} else if(shapeType.equalsIgnoreCase("SQUARE")){
return new Square();
}
return null;
}
}
public class Main{
public static void main(String args[]){
List<Shape> shape=new ArrayList<>();
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/310992.html
標籤:爪哇
下一篇:運算式的非法開始:Java方法
