Understand method overloading and rewriting

Method overloading and rewriting

Method overloading

If there are multiple methods with the same name but different parameters in the same class, it is called method overload; for example, similar to the accumulation operation, because the parameter list is different, so you need to define multiple methods, but this operation is more troublesome, so You can use method overloading.

Conditions for overloading:

  • Must be the same class
  • Method names must be the same
  • The parameter list is different
  • Overloading and return value types have nothing to do with parameters

E.g:

//两个参数相加
public static int add(int a,int b){
        return a+b;
    }
//三个参数相加
public static int add(int a,int b,int c){
    return a+b+c;
}
//四个参数相加
public static int add(int a,int b,int c,int d){
    return a+b+c+d;
}

carried out:

public static void main(String[] args) {
    System.out.println(add(1,2));
    System.out.println(add(1,2,3));
    System.out.println(add(1,2,3,4));
}

operation result:

3
6
10

Method rewriting

The same methods (including return value type, method name, parameter list) appear in the subclass as in the parent class; for example, Xiao Ming wants to inherit the property left by his father one day, but Xiao Ming finds that this house is a little disliked, so he himself The floor was resurfaced, the walls were painted, and the furniture was changed; the process of decorating the house in Xiaoming is called method rewriting in Java.

Conditions for rewriting:

  • Must be implemented under the premise that the subclass inherits the parent class

  • The override method of the subclass must have the same method in the parent class, including return value, method name, parameter list

  • The overridden method can be marked with @Override annotation

  • The access rights of the overridden methods in the subclass cannot be lower than the access rights of the methods in the parent class ( private <default <protected <public )


Guess you like

Origin blog.csdn.net/ITMuscle/article/details/109173341