I’m still quite new to java. So I was reading around polymorphism and static binding while playing around with java. I’m here to clarify if my thinking process is correct.
class A {
void foo(A a) {
System.out.println("AAAAAA");
}
}
class B extends A {
void foo(B a) {
System.out.println("BBBBB");
}
}
class C extends B{
void foo (A a){
System.out.println("CCCCCBBBB");
}
}
I created the following object called "c", and called foo with c as the argument.
C c = new C();
c.foo(c); // the output is BBBBB
From this post Question about Java overloading & dynamic binding, I understand that if the argument sent is not found in the class, it will upcast the argument (in this case C) to what can be found in the class (in this case A, since void foo (A a)). But if that’s the case, shouldn’t it print "CCCCCBBBB". through static binding.
>Solution :
Class C has 2 overloaded methods with the name foo
// defined in the class C
void foo (A a){
System.out.println("CCCCCBBBB");
}
// inherited from the class B
void foo(B a) {
System.out.println("BBBBB");
}
The most specific one will be chosen when we are calling the method foo with the parameter of the class C – the class B is closer by hierarchy than the class A, so foo(B) is called.