MrGuy
MrGuy

Reputation: 664

Copying an Object type of object into a specific type of object

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?

Upvotes: 1

Views: 104

Answers (1)

Fred
Fred

Reputation: 17085

There's a way, although it's usage is not very clean in my personal opinion. here it is

public Triangle(Object obj){
  if (obj instanceof Triangle){
      Triangle other = (Triangle) obj;
      this.p1 = new Point(other.p1);
      this.p2 = new Point(other.p2);
      this.p3 = new Point(other.p3);
  }
...
}

Why do I think this is not very clean? Well for starts I have no idea what to do if the object is not a Triangle. You'd have to figure that out, meaning what would you do if that constructor receives an object which is not a Triangle? Throw an exception? Not sure... This normally doesn't happen in methods such as equals where the instanceof is used often, because then you know you just return false.

However, at least you know how you can "recognize an object as triangle".

Hope this helps

Upvotes: 1

Related Questions