Reputation: 1028
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.
Upvotes: 2
Views: 2835
Reputation: 420
I do not really understand what you are trying to accomplish here, but off course you can differ cases in form of
shape.getClass().isAssignableFrom(Square.class) ? processSquare((Square)shape) : processCircle((Circle)shape)
There will be no Problem with that cast, if you first check the actual class.
edit Your shapes class type does not change :
Shape[] shapes = new Shape[]{new Circle()}
as you are looping through your shapes collection, when you call shapes[0].getClass()
you will get the Circle.class
type. So at the point where you iterating your shape collection and need to decide which type specific collection to call, you can call shape.getClass().isAssignableFrom(Circle.class)
for example, to switch cases. Then you can cast the type and call the method you need. No need to hold your shape object in differnt collections
Upvotes: 1
Reputation: 2524
Once you declare a reference in Java you cannot change his type. When you do:
Shape shape = someObject.getShape();
You are saying: "store a reference to a Shape in the variable shape". Since you cannot change its type it has no sense doing
shape = (Square) shape;
because you are saying that shape (left side) is a Shape, no matter what is on the right side on the assignment.
Remember: once you declare a type for a reference you cannot change it.
Upvotes: 1
Reputation: 137312
You need to declare the variable properly, for example:
if (shape instanceof Square){
Square square = (Square) shape;
// do this with square
} else if (shape instanceof Circle) {
Circle circle = (Circle) shape;
// do that with circle
}
Upvotes: 7