Also remember that method overriding is not method overloading.
It’s impossible to override a method if the parameters are different. It is possible to change the return type of the overridden method if the return type is a subclass of the superclass method.
What to remember about polymorphism
- The created instance will determine what method will be invoked when using polymorphism.
- The
@Override
annotation obligates the programmer to use an overridden method; if not, there will be a compiler error. - Polymorphism can be used with normal classes, abstract classes, and interfaces.
- Most design patterns depend on some form of polymorphism.
- The only way to use a specific method in your polymorphic subclass is by using casting.
- It’s possible to design a powerful structure in your code using polymorphism.
- Run your tests. Doing this, you will be able to master this powerful concept!
Learn more about Java
- Get more quick code tips: Read all of Rafael's articles in the InfoWorld Java Challengers series.
- Check out more videos in Rafael's Java Challengers video playlist.
- Find even more Java Challengers on Rafael's Java Challengers blog and in his book, with more than 70 code challenges.
This story, "Polymorphism and inheritance in Java" was originally published by JavaWorld.