php editor Xigua often receives questions about polymorphism and static binding in Java. These two concepts are often mentioned in Java but can be confusing for beginners. In this article, we will briefly introduce the concepts of polymorphism and static binding and answer some frequently asked questions to help readers better understand and apply these concepts.
I am still very new to java. So I was playing around with java while reading about polymorphism and static binding. I'm here to clarify if my thought 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 named c
and called foo with c as argument.
C c = new C(); c.foo(c); // the output is BBBBB
From this question about java overloading and dynamic binding, I understand that if the parameter sent is not found in the class, it will up-cast the parameter (c in this case) to the one in the class The argument can be found (in this case a, because void foo (a a)
). But if that's the case, shouldn't it print "cccccbbbb"? Via static binding?
Class c
has 2 overloaded methods named 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"); }
When we call a method foo
with arguments of class c
, the most specific one will be chosen - class b
which is hierarchically smaller than class a
is closer, so foo(b)
is called.
The above is the detailed content of Confused about polymorphism and static binding in Java. For more information, please follow other related articles on the PHP Chinese website!