【JAVA SE】The difference between "rewriting" and "overloading"

Kind tips

Hello everyone, I am Cbiltps. In my blog, if there are sentences that are difficult to understand or key points that are difficult to express in words , I will have pictures . So my blog with pictures is very important ! ! !

The knowledge points in this section are extracted from my main blog . The main blog actually serves as an expanded context to reflect the logical order for all knowledge points . Therefore, I will pull out the things that are worth discussing in it separately, so that everyone can eat them!

Corrections/additions are welcome, come on!

start of text

Override (Override): The subclass inherits the original method of the parent class, but sometimes the subclass does not want to inherit a method in the parent class intact, so in the method name , parameter list , return type (except the subclass When the return value of the method in the parent class is the same as the return value of the method in the parent class), the method body is modified or overwritten . That is, the shell remains unchanged, but the core is rewritten!

  • The return value of the two methods rewritten ( 除了上面写到的special timeand the subclass of the return value type of the overridden method) , the method name , and the parameter list must be completely consistent (the subclass overrides the method of the parent class)
  • The access level of the subclass method cannot be lower than the access level of the corresponding method of the parent class
  • The exception thrown by the overridden method is consistent with the exception thrown by the overridden method , or its subclass (the subclass exception cannot be greater than the parent class exception)
  • Methods decorated with private , final and static cannot be overridden

Overload: In a class, methods with the same name are considered overloaded if they have different parameter lists ( different parameter types , different numbers of parameters , or even different order of parameters ). At the same time, overloading has no requirement on the return type , which can be the same or different, so the overload cannot be judged by whether the return type is the same .

  • The method name is the same, but the parameter list is different (parameter order, number, type)
  • Method return value, access modifier any

Note and difference summary:

  • Overriding implements is 运行时的多态, while overloading implements编译时的多态
  • Overridden method parameter lists must be the same ( 一般情况下) ; and overloaded method parameter lists must be different
  • The return value type of the overridden method can only be the parent class type or a subclass of the parent class type , while the overloaded method has no requirement for the return value type

insert image description here

Guess you like

Origin blog.csdn.net/Cbiltps/article/details/122550276