Reputation: 433
Here is the code:
class Override {
public static void main(String[] args) {
A a = new A(1, 2);
A a1 = new B(1, 2, 3);
B b = new B(4, 5, 6);
a.show();
a1.show();
b.show();
}
}
class A {
int a;
int b;
A(int a, int b) {
this.a = a;
this.b = b;
}
void show() {
System.out.println(a + " " + b);
}
}
class B extends A {
int c;
B(int a, int b, int c) {
super(a, b);
this.c = c;
}
void show() {
System.out.println(c);
}
}
Restult:
1 2
3
6
A reference variable of a superclass can be assigned to an object of any subclass derived from that superclass. The type of the reference variable determines what member can be access.
Based on the fact above, a1 cannot access to c(member of B), since a1 doesn't know the existence of any member in B. My question is when a1 calls on show(), why is the show() in B being invoked instead of that of A?
Thank all of you for your answers.
Here is something I think very interesting:
Dynamic method dispatch is a mechanism by which a call to an overridden method is resolved at run time. When an overridden method is called through a superclass reference, java determines which version of that method to execute based on the type of the object being referred to at the time the call occurs.
Upvotes: 0
Views: 90
Reputation: 26506
The function from B will be called. this mechanism is called "Virtual Functions". if a subclass overrides a function in the base class , the program will search the right function on run time and invokes it for the right type (B and not A). in Java , all functions are virtual.
but your question is right , though , in C++ and C# , the functions are not virtual by default, if they are not declared as virtual explicitly , the function from A will be called (in equivalent C++/C# code);
Upvotes: 0
Reputation: 37604
Because your class B
overrides the show()
method. The superclass method is only used if the inheritor does not override it.
Upvotes: 0
Reputation: 201507
Because B
has overridden the method show()
the show()
in B
is invoked. Consider an abstract
method, if B
couldn't replace the abstract method it could never be implemented (likewise with interfaces).
abstract void show();
Finally, if the method shouldn't be overridable make it private
. The default level of access is inherited.
Upvotes: 1