Say I have the following classes
public abstract class Parent { public Parent() { //stuff here } } public class Child extends Parent { public Child() { //stuff here } public void doSomething() { } }
Then I get an object from an array of Parents
public Parent[] parents = new Parent[5]; Parent tempParent = parents[0]
If this object is of the child class, I want to cast the tempParent into the child class in order to use “doSomething” without having to create a new object
if(tempParent.getClass == Child.class) { tempParent = (Child) tempParent; tempParent.doSomething(); }
This, however, does not work. I still get an error telling me that doSomething is not a function in the Parent class. Is there a way to do what I’m trying to do?
Advertisement
Answer
You need to use the correct TYPE on the LEFT hand side:
Child someChild = (Child) tempParent;
Note: this does not create a new Object.
There is no way of having
Parent whatever = (Child) tempParent;
do what you want to do (invoke a Child class method)!
You see, the compiler only cares about the “defined” type of your reference, it does not take into account that you most likely, at runtime, just “put” something into that reference that in deed is a Child instance!
to do what you want to do.
And note: do not compare objects using ==
. You should prefer to call equals()
instead. For Class
objects ==
should work (most of the time), but still: get used to check for equality using equals()
.