【发布时间】:2022-11-07 19:51:23
【问题描述】:
我有一些课程Shape。
public abstract class Shape {
String shapeColor;
public Shape(String shapeColor){
this.shapeColor = shapeColor;
}
abstract public double calcArea();
@Override
public String toString() { return "Shape"; }
public String getShapeColor() { return shapeColor; }
}
此外,我还有从 Shape 扩展的类:Triangle、Rectangle 和 Circle。
public class Triangle extends Shape {
double a, h;
public Triangle(String shapeColor, double a, double h) {
super(shapeColor);
this.a = a;
this.h = h;
}
@Override
public double calcArea() {return a * h / 2;}
@Override
public String toString() {
return "Triangle";
}
}
public class Rectangle extends Shape {
double a, b;
public Rectangle(String shapeColor, double a, double b) {
super(shapeColor);
this.a = a;
this.b = b;
}
@Override
public double calcArea() {
return a * b;
}
@Override
public String toString() {
return "Rectangle";
}
}
public class Circle extends Shape {
double r;
public Circle(String shapeColor, double r) {
super(shapeColor);
this.r = r;
}
@Override
public double calcArea() {
return (Math.PI * r * r);
}
@Override
public String toString() {
return "Circle";
}
}
我想创建Arraylist<Shape> shapes 并根据用户输入为其添加形状。
所以,我想要类似的东西
String[] userInput = scanner.nextLine().split(", ");
Shape shape = createNewShape(userinput)
例如:
"Circle, Blue, 7" -> Shape shape = new Circle("Blue", 7)
"Rectangle, Red, 5, 10" -> Shape shape = new Rectangle("Red", 5, 10)
但即使创建了从 Shape 扩展的新类,我也希望它能够正常工作。
例如,如果我有新的Shape Cube,我就不需要在我的代码中添加一些东西:
"Cube, Red, 9" -> Shape shape = new Cube("Red", 9)
这个question 接近我需要的,但是我的类有不同数量的参数。也许有人可以给我一条建议,如何让它适用于不同数量的参数。
【问题讨论】:
-
顺便说一句,“不同数量的参数”不应该成为创建新问题的理由(尽管我不会为此使用反射,可能是
Shape的工厂方法中的简单switch) -
我不想在 Shape 中切换,因为这将迫使我每次获得新 Shape 时添加新案例,例如新 Shape Cube、Pyramid 或其他。
标签: java