Home > Java > body text

Confused about polymorphism and static binding in Java

PHPz
Release: 2024-02-11 09:30:08
forward
611 people have browsed it

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.

Question content

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");
    }

}
Copy after login

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
Copy after login

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?

Solution

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");
}
Copy after login

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!