Current location - Quotes Website - Personality signature - Briefly describe the difference between rewriting and overloading.
Briefly describe the difference between rewriting and overloading.
Override (override)

1, method name, parameter and return value are the same.

2. Subclass methods cannot narrow the access rights of parent methods.

3. Subclass methods can't throw more exceptions than parent methods (but subclass methods don't have to throw exceptions).

4. It exists between the parent class and the subclass.

5. This method is defined as the final method and cannot be rewritten.

Overload (overload)

1, there is at least one difference in parameter type, number and order.

2. Method names with different return values cannot be overloaded.

3, exists in the parent class and subclass, the same kind.

Overwriting and overloading of methods are different manifestations of Java polymorphism.

Rewriting is the expression of polymorphism between parent class and subclass, while overloading is the expression of polymorphism in a class.

If a method defined in a subclass has the same name and parameters as its parent class, we say that the method is overridden. When an object in a subclass uses this method, it will call the definition in the subclass. For it, the definition in the parent class seems to be "shielded".

If multiple methods with the same name are defined in a class, they either have different parameter numbers, different parameter types or different parameter orders, which is called method overloading. Exceptions that cannot be overloaded by access rights, return types, and.

1. Override function

1, the flag of the covered method must completely match the flag of the covered method to achieve the coverage effect;

2. The return value of the overridden method must be consistent with the return value of the overridden method;

3. The exception thrown by the overridden method must be consistent with the exception thrown by the overridden method, or be a subclass of it;

4. The overridden method cannot be private, otherwise it just defines a new method in the subclass and does not override it.

2. Overload characteristics

1. Overloading can only use different parameter styles. For example, the parameter types are different, the number of parameters is different, and the order of parameters is different (of course, several parameter types in the same method are definitely different, for example, it can be fun (int, float), but not fun(int, int)););

2. It cannot be overloaded by access rights, return types and exceptions thrown.

3. The type and number of method exceptions will not affect overloading;

4. For inheritance, if the access right of the method in the parent class is priavte, then it cannot be overloaded in the subclass. If it is defined, it only defines a new method, and it will not achieve the effect of overloading.