Method overloading and method rewriting explanation

Method overloading:

  1. Use: It is often used in the declaration of methods in the same class . According to different parameter lists (number of parameters, different types, and parameter order (must be different in order of parameters with different types)), different methods with the same name can be declared and executed in the program. Bind the corresponding method at compile time during the process

    Note: Whether overloading occurs has nothing to do with the return value type

  2. example:

    public static void say(){
        System.out.println("Hello");
    }
    public static void say(String name){
        System.out.println("Hello, my name is"+name);
    }


Method override:

  1. Use: It is often used in the declaration of methods in parent and child classes. Generally, abstract will be used in superclasses/interfaces to set methods as abstract methods (only method names, no method bodies, including curly braces), and subclasses to implement method rewriting , parameters must be the same

  2. Note: Rewriting should follow the principle of "two the same, two small and one big":

    1. Two same:

      • same method name

      • The parameter list is the same

    2. Two small:

      • The return value type of the subclass method is less than or equal to that of the parent class

        • must be equal when void

        • Must be equal when primitive type

        • Less than or equal when referring to types: the parent class is larger, and the child class is smaller

      • The exception thrown by the subclass is less than or equal to that of the parent class

    3. One big: the access rights of subclass methods are greater than or equal to those of the parent class

  3. example:

    interface Aoo{
        public abstract void say();
    }
    public class Boo implements Aoo{
        public void say(){
            System.out.println("Hello");
        }
    }


Guess you like

Origin blog.csdn.net/m0_69270622/article/details/129957480
Recommended