The difference between rewriting and overloading in Java
In fact, rewriting and overloading in Java have nothing to do with it. It’s just that because there are heavy words, some novices will confuse these two concepts, so many interviewers like to ask this question.
Both overloading and rewriting methods in Java are ways to implement polymorphism. The difference is that the former implements compile-time polymorphism, while the latter implements run-time polymorphism.
- Overload occurs in a class. If a method with the same name has a different parameter list (different parameter types, different number of parameters, or both), it is considered an overload;
- Rewriting occurs between the subclass and the parent class. Rewriting requires that the subclass rewrite method and the parent class rewrite method have the same return type, which is better access than the parent class rewrite method, and cannot declare more exceptions than the parent class rewrite method (LSP Rich's replacement principle).
- Overloading has no special requirements for return types.
Method overloading rules
- The method names are the same (exactly the same), and the order, type and number of parameters in the parameter list are different.
- Overloading is independent of the return value of the method and exists in a class.
- Different exceptions can be thrown, and different modifiers can be included.
Method rewriting rules
- a. The parameter list must be exactly the same as the rewritten method, and the return type must be exactly the same as the return type of the rewritten method. That is, the body of the method is the same, the difference is the contents of the method body.
- b. The constructor cannot be rewritten, the method declared as final cannot be rewritten, and the method declared as static cannot be rewritten, but can be declared again.
- c. Access permissions cannot be lower than access permissions for overwritten methods in the parent class.
- d. The rewritten method can throw any unchecked exception (UncheckedException, also known as a non-runtime exception), regardless of whether the rewritten method throws an exception. However, a rewrite method cannot throw new mandatory exceptions, or a wider range of mandatory exceptions declared by the rewrite method, otherwise it can.
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.