suppose I have this class:
class B extends A
{
@Override
void foo () { ... }
}
Now if I am given an object of class B can I explicitly invoke the foo method from class A? I tried downcasting the object i.e.,
B b = new B();
((A)b).foo();
but that doesn't seem to work.
So is there a way to accomplish what I would like to do in Java?
Always method invocation will be on type of the
object
due to polymorphism.In this case even though you down cast, object is of type
B
, sofoo()
method fromClass B
will be invoked.This sun tutorial may help you.