So I have (skipping some detail) the following:
public abstract class BaseObject implements IObject {
public abstract void setMethod();
}
public class ChildObject extends BaseObject implements IObject {
public void setMethod() {
// Child implementation
}
}
public class GrandChildObject extends ChildObject {
@override
public void setMethod() {
// grand Child implementation
}
}
then when I am in a method
public void testThis(Object o) {
((IObject) o).setMethod();
}
it executes the ChildObjects implementation
so I tried this
public void testThis(Class GrandChildClass, Object o) {
IBaseObject myObject = (IBaseObject) GrandChildClass.cast(o);
myObject.setMethod();
}
but it still executes the Child method!
How can I execute the GrandChild method from testThis without directly
casting it to a grand child?
thanks
Tim
Danno - 18 Sep 2006 18:34 GMT
> So I have (skipping some detail) the following:
>
[quoted text clipped - 41 lines]
>
> Tim
Strange code not withstanding. An object can never change
implementation eventhough you are calling it with a different pointer.
So if you create a grandchild object and even though you cast it to a
superclass pointer it is still going to be grandchild. Same rules apply
for child, and Base Object. Once an object is created you can't change
what it is.
BTW, my suggestion is you may want to make it easy on yourself and
clean up your code to keep it simple.
Chris Uppal - 19 Sep 2006 11:10 GMT
> How can I execute the GrandChild method from testThis without directly
> casting it to a grand child?
You don't have any choice With or without casting (which has no effect on
virtual method invocation). It will /always/ call the GrandChildObject's
overriding method.
If your real code is the same as your posted example then it will work[*]. So,
presumably, it isn't the same. I can't guess what's going wrong, without
seeing the real code. You should create a /short/, working (or rather,
not-working ;-), complete, and self-contained example; and if the process of
creating it doesn't show you the error (it often does) then post it here.
BTW, just in case it's not an oversight, you don't need to declare that
ChildObject implements IObject -- it does so anyway since it inherits it from
BaseObject.
-- chris
[*] You can easily verify that your example code /does/ work.