1. Overwrite (override)
Overrides are subclasses of the implementation of the method that allows access to the parent class to be rewritten! Neither the return value nor the formal parameter can be changed. That is, the shell does not change, the core rewrite!
- The parameter list and the return value type must be the same as the overridden method.
- Access must be lower than the permission of the overridden method in the parent class.
- The parent class member method can only be overridden by a quilt class.
- The final and static modified methods cannot be overridden, but the static method can be declared again.
- Parent class methods cannot be inherited, they cannot be overridden
- The parent class and subclass are within the same package, and the subclass can inherit all the methods of the parent class except the final decoration, and the private adornment.
- The parent class and subclass are different packages, public and protected, and non-final decorated methods.
- The construction method cannot be overridden.
- The overriding method can throw any non-mandatory exception, regardless of whether the overridden method throws an exception. However, the overriding method has a more extensive exception than the overridden method.
Use of the Super keyword
Use the Super keyword when you need to call the overridden method of a parent class in a subclass.
Overloading (overload)
Overloading (overloading) is a class in which the method name is the same and the parameters are different. What about the return type? can be the same or different.
Each overloaded method (or constructor) must have a unique list of parameter types.
Constructors can only be overloaded
Overloading rules
- The overloaded method must change the parameter list;
- The overloaded method can change the return type;
- Overloaded methods can change the access modifier;
- Overloaded methods can declare new or broader check exceptions;
- Methods can be overloaded in the same class or in a subclass.
The difference between overriding and overloading
Distinguishing points |
Overloaded Methods |
overriding Method |
Parameter list |
Must be modified |
Must not be modified |
return type |
can modify |
Must not be modified |
Abnormal |
can modify |
can be reduced or deleted, must not throw new or wider exceptions |
Access |
can modify |
Must not be more restrictive (can reduce the limit) |
Java override (Override) vs. overload (overload)