どのようにJavaで異なる種類のリストを作成する多型を使用するには?

アリレザBideli:

私は3クラス持っているサークル、長方形や正方形を

私は、上記のクラスのそれぞれに必要なデータを取得し、ユーザーがそれらを作成したいです。

これは、その意味、ユーザーがこれまでに例えば3、欲しいものを作ることができます、2つの長方形と7つの正方形形状の数は、それがユーザーに依存します。

その後、私はそれらを保存したいユニットのリストとしている私のクラスのメソッド呼び出しcalculateAreacalculatePerimeterをし、自分の名前とそれらの周囲と面積を示しています。

どのように私はそれを行うことができますか?

これらは私のクラスであります

サークル

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;
    }
}
スワップニル・パティル:

あなたは、インターフェイスを定義することができますし、すべてのクラスが、このインタフェースを実装します。インターフェイスにすべての一般的なメソッドを追加します。

public interface Shapes {
   public double calculateArea();
   public double calculatePrimeter();
}

これで、すべての形状クラスのは、上記のインタフェースを実装し、インタフェースのメソッドに実装を提供します。あなたのケースでは、すべてのメソッドの戻り値の型を変更します。あなたはそれが倍に保つことができます。

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{}

そして、あなたは1つのリストを持っている必要があります

static List<Shapes> unitList = new ArrayList<Shapes>();

上記のリストにユーザー&アドオンからの入力を取得します。そして、単にループunitList&それぞれのメソッドを呼び出します

エリアを計算します

for (Shapes shape : unitList)
    System.out.println("Area: " + shape.calculateArea());

境界を計算します

for (Shapes shape : unitList)
    System.out.println("Perimeter: " + shape.calculatePrimeter());

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=182400&siteId=1