Reputation: 395
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?
Upvotes: 0
Views: 114
Reputation: 1499770
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:
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.
Upvotes: 5
Reputation: 2830
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. I.e one is Object
the other - String
.
Upvotes: 0