Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Confused about polymorphism and static binding in JAVA

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading