Reputation: 215
I have 2 classes, one which extends the second one and overrides some of the methods of the parent. When I call fs.m(ff)
I got a weird result, and I can't figure out why does it happen. type First fs
shouldn't have access to class Second methods, even if we assigned a new Second object to them, unless we casted it like that - (Second) fs.m(ff)
. Could anyone please explain why does this code produce output "override"?
public class Main {
public static void main(String[] args) {
First ff = new First();
First fs = new Second();
Second ss = new Second();
System.out.println( fs.m(ff));
}
}
public class First {
public String m(First x){
return "default";
}
public String m(First x, First y){
return "default";
}
}
public class Second extends First{
public String m(Second x){
return "overload";
}
public String m(First x){
return "override";
}
public String m(First x, Second y){
return "???";
}
}
Upvotes: 2
Views: 50
Reputation: 1661
Fs is actually pointing a Second Object (fs is a reference to an object of type Second). So when you call fs.m(ff) it is actually calling the object on Second due to dynamic binding (override).
Upvotes: 0
Reputation: 393771
The method invoked for fs.m(ff)
is determined by the runtime type of fs
. That runtime type is Second
, and since Second
overrides the public String m(First x)
method, that method is executed.
fs
has access do the methods declared in First
class, since it is of type First
, but during runtime, the actual methods that get executed depend on whether those methods are overridden by the run-time type of the instance assigned to fs
, which is Second
.
Upvotes: 3