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 =
You can just create an ArrayList
. That's a list that can store anything. It's not very useful to work with, because taking things out basically forces you to check their type in order to call any methods. For that reason you should almost always avoid doing this.
Objects in collections usually have something in common - if they don't, you should rethink why you're throwing them into the same collection. In your case, they're all shapes. So instead, consider adding a shared interface such as Shape
which combines the common functionality.
I'm simplifying slightly because you have the concept of both 2D and 3D shapes, but here's the gist:
interface Shape
{
double area();
double perimeter();
}
class Circle implements Shape
{
// ...
public double area()
{
return radius * radius * Math.PI;
}
public double perimeter()
{
return 2 * Math.PI * radius;
}
}
class Square implements Shape
{
//...
}
And then creating a list of Shape
s:
List shapes = Arrays.asList(new Circle(3), new Square(4), ...);