So I'm trying to make an array of (different) objects (one of those defined in the 'Triangle' class), after messing around with it for a while, this is what I've got:
public class ShapeContainer {
private Object objects [];
private int _size;
public static final int init_size = 3;
public ShapeContainer(ShapeContainer other){
this.objects = new Object[other.objects.length];
this._size = other._size;
for(int i=0; i<_size ;i++){
if (other.objects[i].getClass().equals(Triangle.class)){
this.objects[i] = new Triangle(other.objects[i]);
}
}
}
}
For that to work I've made a new constructor in the Triangle class(note: Triangle is built out of 3 Point objects: Point p1, Point p2, Point p3. Every Point object is built out of 2 double variables: x,y):
public Triangle (Object obj){
this.p1 = new Point(obj.p1);
this.p2 = new Point(obj.p2);
this.p3 = new Point(obj.p3);
}
And now the problem is that I can't refer to obj.p1/obj.p2/obj.p3 because "Object obj" isn't recognized as a Triangle object.
So basically, is there a way to make a generic Object recognized as a specific object? If not, how'd you approach this?
Triangle) for your array variable. If you need to hold multiple different types of shape, create aShapeinterface or abstract class and useTriangle extends Shape.(TheSubclassName)theSuperclassReference. (Just don't fall into the trap of believing that a cast "converts" an object from one type to another. The object must already be the cast-to type.)