filmov
tv
Learn Java Programming - Polymorphism Instance Method Overriding Rules Tutorial

Показать описание
The JVM determines which instance method to invoke based on the type of the object, not the type of the reference variable. Because overriding instance methods form the cornerstone of polymorphism, it is necessary to go over some of the rules that apply to overriding methods.
If a superclass method is public, then the subclass method must also be public. Weaker access will cause a compiler error.
If a superclass method is protected, then the subclass method can be either protected or public. Weaker access will cause a compiler error.
If a superclass method has no-access modifier, aka default access, then the subclass method can be either default, protected, or public. Private access will cause a compiler error.
If a superclass method is private, then the subclass method can be anything. Overriding is NOT occurring in this case. Private methods are not visible and not inherited. You would simply be declaring a new method in the subclass.
The parameter list must be identical. If it is different, then you just created an overloaded method.
If a superclass method is final, then the method cannot be overridden.
The return type in the subclass must be the same (or a subtype - covariant return) as the superclass.
There are a few more rules that are beyond the scope of this tutorial with regards to the series thus far. I will be discussing covariant method returns and exception handling shortly. After I cover those topics, I will go over any additional rules in a future tutorial.
If a superclass method is public, then the subclass method must also be public. Weaker access will cause a compiler error.
If a superclass method is protected, then the subclass method can be either protected or public. Weaker access will cause a compiler error.
If a superclass method has no-access modifier, aka default access, then the subclass method can be either default, protected, or public. Private access will cause a compiler error.
If a superclass method is private, then the subclass method can be anything. Overriding is NOT occurring in this case. Private methods are not visible and not inherited. You would simply be declaring a new method in the subclass.
The parameter list must be identical. If it is different, then you just created an overloaded method.
If a superclass method is final, then the method cannot be overridden.
The return type in the subclass must be the same (or a subtype - covariant return) as the superclass.
There are a few more rules that are beyond the scope of this tutorial with regards to the series thus far. I will be discussing covariant method returns and exception handling shortly. After I cover those topics, I will go over any additional rules in a future tutorial.
Комментарии