Java – How to create an object of an ArrayList in java

arraylistarraysjavaobjectshapes

I want to create a new object of an ArrayList Of Shape. The ArrayList contains shapes, rectangle, ellipse etc… ArrayList<Shape> shapes = new ArrayList<Shape>();
The new object must contain the shapes that it holds and a text attribute to name the shape. This is what i want to achieve:

How can I do this?

EDITED

Here is what i wanted to say
enter image description here

I've reached here! Now i want java to write it as "Student is linked to ID"

enter image description here

Best Answer

1. Create an interface Shape -

interface Shape {

}  

2. Now each of the shape - rectangle, ellipse etc can implement the Shape interface -

Rectangle implements Shape{
 String name;
 // other properties as required

  //constructor as your requirement
  //getters setters as your requirement
}

Or -

Ellipse implements Shape{
     String name;
     // other properties as required

     //constructor as your requirement
     //getters setters as your requirement

    }

3. Now create an ArrayList of Shape -

ArrayList<Shape> shapes = new ArrayList<Shape>)();

Since both Rectangle and Ellipse implements Shape the ArrayList shapes can hold both type of object. After that you can write -

Rectangle r = new Rectangle();
Ellipse e = new Ellipse();
shapes.add(r);
shapes.add(e);  

Hope it will help.
Thanks a lot.