The difference between overriding and overloading in Java

The premise of method overriding: There must be an inheritance relationship.

Method rewriting: The sub-parent class has a function with the same name, which we call method rewriting.

When to use method overriding: When the function of the parent class cannot meet the needs of the child class.

Points to note when overriding methods:
    1. When a method is overridden, the method name and the formal parameter list must be consistent.
    2. When the method is overridden, the permission modifier of the subclass must be greater than or equal to the permission modifier of the parent class.
    3. When the method is overridden, the return value type of the subclass must be less than or equal to the return value type of the parent class.
    4. When the method is overridden, the exception type thrown by the subclass should be less than or equal to the exception type thrown by the parent class.
            Exception (worst)
            RuntimeException(小坏)

Method overloading: There are two or more functions with the same name in a class, which is called method overloading.

Method overloading requirements
   1. The method name must be the same.
   2. The parameter table of the method must be different, including the type or number of parameters, so as to distinguish different method bodies.
        1. If the number of parameters is different, regardless of its parameter type!
        2. If the number of parameters is the same, the type of the parameters or the order of the parameters must be different.
   3. The return type and modifier of the method can be the same or different.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325652656&siteId=291194637