java - 如何使用多态性在java中创建具有不同类型的列表?
我有 3 个课程圆形、矩形和方形
我想获取上述每个类所需的数据并由用户创建.
I want to get required data for each of above classes and create them by user .
表示用户可以想要什么,例如 3 个 Circles 、2 个 Rectangles 和 7 个 Squares .形状的数量取决于用户.
It means that user can make what ever wants ,For example 3 Circles ,2 Rectangles and 7 Squares . The number of shapes it depends on the user.
然后我想将它们保存在 unit list 中并调用我的类方法,它们是 calculateArea 和 calculatePerimeter 并显示周长和面积其中有他们的名字.
Then I want to save them in a unit list and call my classes methods ,which are calculateArea and calculatePerimeter and show perimeter and area of them with their name .
我该怎么做?
这是我的课
圈子
public class Cricle {
private int radius;
public Cricle(int radius) {
this.radius = radius;
}
public double calculateArea()
{
return (radius*radius)*Math.PI;
}
public double calculatePerimeter()
{
return (radius*2)*Math.PI;
}
}
矩形
public class Rectangle {
private int width;
private int height;
public Rectangle(int width, int height) {
this.width = width;
this.height = height;
}
public int calculateArea() {
return width*height;
}
public int calculatePrimeter() {
return (width+height)*2;
}
}
方形
public class Square {
private int edge;
public int calculateArea() {
return edge*edge;
}
public int calculatePrimeter() {
return edge*4;
}
}
推荐答案
你可以定义一个接口,你所有的类都会实现这个接口.将所有常用方法添加到接口中.
You can define an interface and all your classes will implement this interface. Add all common methods into an interface.
public interface Shapes {
public double calculateArea();
public double calculatePrimeter();
}
现在你所有的形状类都将实现上述接口并提供接口方法的实现.在您的情况下,更改所有方法的返回类型.你可以把它加倍.
Now all your shape class's will implement the above interface and provide implementation to interface methods. In your case change the return type of all your methods. you can keep it double.
public class Circle implements Shapes{
private int radius;
public Circle (int radius) {
this.radius = radius;
}
@Override
public double calculateArea() {
return (radius * radius) * Math.PI;
}
@Override
public double calculatePrimeter() {
return (radius * 2) * Math.PI;
}
}
public class Rectangle implements Shapes{}
public class Square implements Shapes{}
那么你需要有一个列表
static List<Shapes> unitList = new ArrayList<Shapes>();
从用户那里获取输入 &添加到上面的列表中.然后简单地循环 unitList
&调用各自的方法
Get inputs from the user & add to the above list. Then simply loop unitList
& call respective methods
用于计算面积
for (Shapes shape : unitList)
System.out.println("Area: " + shape.calculateArea());
用于计算周长
for (Shapes shape : unitList)
System.out.println("Perimeter: " + shape.calculatePrimeter());
相关文章