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

后端 未结 5 1297
北荒
北荒 2020-12-22 04:30

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 me

5条回答
  •  自闭症患者
    2020-12-22 05:07

    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 unitList = new ArrayList();
    

    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());
    

提交回复
热议问题