How to use polymorphism to make list with different types in java?

Alireza Bideli :

I have 3 Classes Circle, Rectangle and Square

I want to get required data for each of above classes and create them by user .

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.

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 .

How can I do It?

These are my classes

Circle

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

Rectangle

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

Square

public class Square {
    private int edge;


    public int calculateArea() {
        return edge*edge;
    }

    public int calculatePrimeter() {
        return edge*4;
    }
}
Swapnil Patil :

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

Then you need to have one list

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

Get inputs from the user & add to the above list. Then simply loop unitList & call respective methods

For calculating Area

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

For calculating Perimeter

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=71571&siteId=1