Detailed explanation and examples of Java overload and override

Many students don't know the difference between overload and override. It is recommended not to memorize conceptual knowledge by rote, but to understand and remember.

Give my definition first:

Overload: a group of method groups with the same name and different parameters in the same class or class with inheritance relationship. In essence, it is the name of different methods.

Override: between two classes with inheritance relationship, the methods existing in the parent class are redefined in the subclass. The essence is to give different implementations for the same method.

Let's take an example of overloading:

Observe:

(1) There are four methods with the same name in overloadparent

(2) The parameter types and numbers of the first three methods are inconsistent, and the return values are consistent, forming an overload

(3) The return value of method 4 is different from that of method 1. It does not constitute an overload and the compiler does not pass.

PS: the return value is the result after the method is executed. When calling the method, we will not specify that "I want to call a method with the return value of XXX", which cannot become the feature of method overloading.

(4) Overloadparent inherits the demo and owns all the methods in the demo. It feels that the existing methods can not meet the requirements and simply overloads one.

Overloaded flag: the method name is the same, the parameters are different (number or type), and it has nothing to do with the return value.

Let's take another example of overwriting:

What will be output when overridechild's main method is executed?

The answer is: I can't fly, but I can run!

We see:

(1) Both overridechild and overrideparent have a fly method

(2) The return value and modifier of fly are the same, except for the method body

(3) There is a @ overwrite annotation in front of the fly method of the subclass. It appears in JDK1.5 and is only used for class inheritance. 1.6 can be used for interface implementation. This annotation is helpful for compiler inspection and can be used without.

Overridden flag: the child inherits the parent class and has different implementations for the same method.

Application scenario

Overloading: when methods have similar functions, but need to pass different parameters.

Override: a subclass has its own unique behavior. It inherits from the parent class and cannot meet its own needs.

PS: overloading and overwriting are polymorphic expressions. The former is compiler polymorphism and the latter is runtime polymorphism.

Thank you for reading, hope to help you, thank you for your support to this site!

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>