Let’s say I have a super type (Shape) and two children (like Square, Circle).
I’m trying to make something like this:
Shape shape = someObject.getShape();
if (shape instanceof Square){
shape = (Square) shape;
// do this
} else if (shape instanceof Circle) {
shape = (Circle) shape;
// do that
}
Also, since getting instances doesn’t seem a correct OO principle, is there another way doing that? Cheers.
edit. I’m not trying to invoke methods on them, I want to pass them to some methods that need their specific subtype.
edit2 Basically I have a collection of type Shape so I can hold both type of subtypes in it. But when it comes to processing at one point, I need to know which of those two subclasses is, so I can pass it to a method that takes the subtype as an argument. I could easily use the supertype as argument but that wouldn’t be secure, since I deal with subtype-specific data.
You need to declare the variable properly, for example: