Method rewriting VS overloading

Method rewriting ( override)

  1. Method rewriting

    The subclass inherits methods from the parent class. Sometimes, the subclass needs to modify the implementation of the method defined in the parent class. This is called method rewriting ( method overriding). The concept of "rewriting" is similar to "overloading". They are both one of the Java"polymorphic" techniques. The so-called "overloading" means that the method has the same name but can do different things on different occasions. When a subclass inherits a parent class, and the method in the subclass and the method in the parent class have exactly the same name, number of parameters, and types, it is said that the method in the subclass overrides the method in the parent class . "Rewriting" is also called "rewriting" and "overwriting".

  2. How to use rewrite

    class Super {
          
          
     访问权限 方法返回值类型 方法1(参数1{
          
          
         ...
     }
    }
    class Sub extends Super{
          
          
     访问权限 方法返回值类型 方法1(参数1) —————>复写父类中的方法
     {
          
          
         ...
     }
    }
    

Note: Two principles must be followed when the method is rewritten, otherwise the compiler will point out that the program is wrong.

  • The overridden method cannot have stricter access rights than the overridden method;
  • The overridden method cannot generate more exceptions than the overridden method (the exception will be described later).

Method overload ( overload)

  1. Method overloading

    First review the method overloading mentioned earlier. Method overloading means that multiple methods can share the same name, but the number or types of parameters cannot be exactly the same . When calling a method, the compiler determines the currently used method according to the number and type of parameters. Method overloading brings convenience to the writing of programs, which is OOPthe concrete realization of polymorphism. In Javathe class library of the system, many important methods are overloaded, which provides convenience for users to use these methods.

  2. Overloaded rules

    • The overloaded method must change the parameter list (the number or types of parameters are not the same);
    • The overloaded method can change the return type;
    • The overloaded method 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 return value type cannot be used as the criterion for distinguishing overloaded functions.

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_45783660/article/details/114091237