简体   繁体   中英

How Java Picks an Overloaded Method in Polymorphism

I have two classes defined as:

public static class Mammal extends Animal {
    public void info(String s) {
        System.out.print("Mammal");
    }
}

public static class Animal {
    public void info(Object o) {
        System.out.print("Animal");
    }
}

Now I define two variables as:

Mammal m = new Mammal();
Animal a = new Mammal();

When I call m.info("test") , it will print

"Mammal"

When I call a.info("test") , it will print

"Animal"

Why does the Mammal type call the Mammal info() method and the Animal type call the Animal info() method when they are both Mammal objects?

You're overloading the method, not overriding it.

Overloads are chosen at compile time, and when the compile-time type of a is Animal , then a call to a.info("test") can only resolve to the info(Object) method in Animal .

If you want to override the method, you need to use the same signature - specify the @Override annotation to get the compiler to check that for you:

public static class Mammal extends Animal {
    @Override public void info(Object s) {
        System.out.print("Mammal");
    }
}

Now it will print "Mammal" in both cases, because the implementation of the method is chosen at execution-time based on the actual type of the object. Remember the difference between them:

  • Overloading: takes place at compile time, chooses the method signature
  • Overriding: takes place at execution time, chooses the implementation of that signature

I also note that you're using nested classes (as otherwise the static modifier would be invalid). That doesn't change the behaviour here, but it does make other changes to the features of classes. I strongly suggest that you try to work with top-level classes most of the time, only using nested types when there's a really compelling reason to do so.

Because

public void info(Object o) {
    System.out.print("Animal");
}

doesn't overrode

public void info(String s) {
    System.out.print("Mammal");
}

Their signatures are different. Ie one is Object the other - String .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM