You are confusing method overrides and method overloads. In your example, the Cat
class has two methods:
public void speak(String name) // It gets this from its super class public void speak(String name, int lives)
Overloading is a way of defining methods with similar functions, but with different parameters. There would be no difference if you named the method this way:
public void speakWithLives(String name, int lives)
To avoid confusion, the recommendation in java is to use the @Override
annotation when you try to override a method. Therefore:
EDIT: Other answers mention this, but I repeat it for emphasis. Adding a new method has led to the fact that the Cat
class can no longer be represented as Animal
in all cases, thereby eliminating the advantage of polymorphism. To use the new method, you need to reduce it to the Cat
type:
Animal mightBeACat = ... if(mightBeACat instanceof Cat) { Cat definitelyACat = (Cat) mightBeACat; definitelyACat.speak("Whiskers", 9); } else { // Definitely not a cat! mightBeACat.speak("Fred"); }
The code checker in my IDE puts a warning in instanceof
because the keyword indicates a possible rejection of polymorphic abstraction.
source share