Can anyone explain me the result of this execution? I can't notice why each method is called. And how we distinguish the real type vs the apparent type. Thank you :)
public class JavaApplication15 {
public static void main(String[] args) {
A a = new A();
B b= new B();
A ab = new B();
b.f(a);
b.f(b);
b.f(ab);
}
}
public class A {
private final String id="A";
public void f(A x){
System.out.println("Send a fax to "+ x ) ;
}
public String toString(){return id;}
}
public class B extends A{
private final String id="B";
public void f(B x){
System.out.println("Send an email to"+ x ) ;
}
public String toString(){return id;}
}
Result:
Send a fax to A
Send an email to B
Send a fax to B
You are overloading which (per the wikipedia) creates multiple methods of the same name with different implementations. I think you meant to override the
f(A x)
method with thef(B x)
method. Overriding (per the wikipedia) allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its superclasses or parent classes.Based on the surprise expressed in your question, I think you wanted something like