SITUATION: Say I have a class A,a class B which extends A and a class C which extends B.class A has a method hello() which is overridden in class B.
EVENT: Now class C calls hello().
QUESTIONS: Which version will be called?i guess it will be of the class just above in the hierarchy, i.e. B. In any case, how to access the different versions of hello() from C?
RELATED QUESTIONS: By using super we can access the version just above in the hierarchy but how to access the ones higher up the hierarchy? For exa开发者_运维知识库mple, how to access A's hello() from C?
You can't. Only code in B
can use super
to call A.hello()
; and if A, B, and C were all to implement hello()
, it would be impossible for any code in C to access A.hello()
.
In general, code in any class can call its own version of a method, and the version of its immediate superclass, and that's it. There's no way to call any others without the cooperation of the superclass.
Dynamic Method Dispatch Dynamic method dispatch is the mechanism by which a call to an overridden method is resolved at run time, rather than compile time. Dynamic method dispatch is important because this is how Java implements run-time polymorphism. A superclass reference variable can refer to a subclass object. Java uses this fact to resolve calls to overridden methods at run time. Here is how. When an overridden method is called through a superclass reference, Java determines which version of that method to execute based upon the type of the object being referred to at the time the call occurs. Thus, this determination is made at run time. When different types of objects are referred to, different versions of an overridden method will be called. In other words, it is the type of the object being referred to (not the type of the reference variable) that determines which version of an overridden method will be executed. Therefore, if a superclass contains a method that is overridden by a subclass, then when different types of objects are referred to through a superclass reference variable, different versions of the method are executed.
Example: class A
{
int a;
void show()
{
a=10;
System.out.println("a of A : "+a);
}
}
class B extends A
{
int a;
void show()
{
a=20;
System.out.println("a of B : "+a);
}
}
class C extends B
{
int a;
void show()
{
a=30;
System.out.println("a of C : "+a);
}
}
class ambiguity
{
public static void main(String args[])
{
A oa = new A();
B ob = new B();
C oc = new C();
A r;//r is superclass reference variable
r = oa;
r.show();
r = ob;
r.show();
r = oc;
r.show();
}
}
class Abcd{
public void show() {
System.out.println("ABCS");
}
}
class Pqr extends Abcd{
public void show() {
System.out.println("PQR");
}
}
class Xyy extends Pqr{
public void show() {
System.out.println("XYY");
}
}
public class SuperKey {
public static void main(String args[]) {
Xyy xy=new Xyy();
xy.show();
}
}
How to call Abcd show method from Xyy show Method?
精彩评论