How to store different types of objects in ArrayList

前端 未结 5 2028
暗喜
暗喜 2021-01-25 22:20

I need to store different objects in the ArrayList. Objects are similar in nature but different and have different methods.

Circle c = new Circle();  
Cube s =          


        
5条回答
  •  无人及你
    2021-01-25 23:09

    This is what you have to do.

    1. Define a Shape interface..

    2. Implement the interface for Circle and Cube

    3. Create shape objects for Circle and Cube and add these to arraylist..

    Code below:

    public interface Shape {
    
        public void draw();
    
    }
    
    
    
    public class Circle implements Shape {
    
    @Override
    public void draw() {
        System.out.println("Drawing Circle");
    
    }
    
    }
    
    
    
    public class Cube implements Shape {
    
    @Override
    public void draw() {
        System.out.println("Drawing Cube");
    }
    
    }
    
    
    
    public class Simulator{
    
    public static void main(String[] s){
    
        Shape s1 = new Circle();
        Shape s2 = new Cube();
    
        ArrayList shapeList = new ArrayList();
        shapeList.add(s1);
        shapeList.add(s2);
    }
    }
    

提交回复
热议问题