Descriptions of Java method overloading, override, and final

Source: Internet
Author: User
Tags java keywords

Sync blog address: http://august.b3log.org/articles/2012/07/16/1342420675028.html

Yesterday, a group of friends in a group asked if the final method could be reloaded. I did not think that the final method cannot be inherited and cannot be reloaded. Later, I couldn't sleep at night. I always thought it was wrong. When I flipped through the book, I thought it was just nonsense. I realized that these basic concepts were ambiguous after a long time, it is especially common for people who do not want to learn things. With the bloody lessons learned yesterday, I decided to start over again. Today is the beginning of this little note!

I. Heavy Load
Java method overloading means that multiple methods can be created in the class. They have the same method name but have different parameter types. A typical application of Java method Overloading is the use of Java constructor, and method Overloading is also an important manifestation of Java polymorphism.

The following example references thinking in Java and demonstrates the overloaded constructors and methods:

class Tree{        int height;        Tree(){               System.out.println("Plantinga seeding");               height = 0;        }        Tree(int initialHeight){               height = initialHeight;               System.out.println("CreatingNew Tree that is" + height + "feet tall");        }        void info(){               System.out.println("Tree is" + height + "feet tall");        }        void info(String str){               System.out.println(str+":Treeis " + height + "feet tall");        }}public classOverloading {        public static void main(String[] args) {                       Tree tree = new Tree(5);                       tree.info();                       tree.info("overloadingmethod");               //Overloaded Constructor               new Tree();        }}

The output result of the above example is:

Creating new tree that is 5feet tall
Tree is 5 feet tall
Overloading method: tree is 5 feet tall
Planting a seeding

The methods for overloading are described as follows:

1. Each overload method must have a unique list of parameter types.

2. The order of parameters is also sufficient to distinguish two methods. The two methods in the following code are also overloaded.

static void f(String s , int i){}static void f(int i , String s){}

3. the overload mechanism works normally, whether it is defining existing methods in the subclass or its parent class. For example:

class Father{void  method(char c){}void method(float f){}}class Son extends Father{void method(double d){}}

4. It is not feasible to distinguish the overloaded Method Based on the return value of the method. The reason is very simple. For example, there are currently two methods: void F () {} and int f () {return 1;}. When we need to call a method in another place, if we only use F (); To call the method, Java cannot determine which F () method to call.

Ii. Overwrite

Overwriting is also called rewriting. If the subclass defines a method with the same name and parameters as the parent class, we will say this method is overwritten. See the following code:

class Father{void  method(char c){//①}void method(float f){//②}}class Son extends Father{void method(double d){//③}void method(char c){//④}}

We need to differentiate that method ③ is an overloaded method, and method ④ is a rewritten method.

The method rewriting is summarized as follows:

1. in Java, subclasses can inherit the methods of the parent class without rewriting. However, if subclasses do not want to copy the methods inherited from the parent class and want to make certain modifications, in this case, method rewriting is required.

2. When the subclass method overwrites the method inherited from the parent class, the method inherited from the parent class at the subclass level will be hidden. To call this method, you need to use the super keyword, which points to the parent class of the current class

3. When we want to override a method, this is often because the parameter type list of this method is not completely consistent with the method in the parent class, resulting in the method being overloaded rather than the override we want. In this case, we can use the @ override annotation. For example, the following code:

class Father{void  method(char c){//①}void method(float f){//②}}class Son extends Father{@Overridevoid method(double d){//③}}

Run the above Code and the compiler will generate a"Method does not override a mehtodd from its superclass"Error message. Because we want Method ③ To be an overwrite method, but actually it is written as an overload method. Therefore, the @ override annotation can prevent unexpected overloading when you do not want to overload it.

Iii. Final Method

There are two reasons for using the final method. The first reason is to lock the method to prevent any inheritance from modifying its meaning. This is out of design considerations: to ensure that the method behavior remains unchanged in inheritance and will not be overwritten. The second reason is the efficiency. Because the new Java version has been solved, final methods are no longer needed for optimization. Therefore, we can set the method to final only when we want to explicitly prohibit overwriting.

Let's look at the last example for the description of the final method:

class Father{private final void method(){//①}}class Son extends Father{private final void method(){//②}}

Do you think there is a problem with the above Code? Otherwise, the above Code is valid. Not that the final method mentioned above cannot be overwritten is wrong, but we should note that the method here is actually private ), private methods cannot be inherited. So here we can understand that method ② is a brand new method defined in the subclass, rather than rewriting the parent class method.

PS: This is the first time I wrote a technical blog. I hope to help myself better understand the knowledge and help more people!

Link: This article summarizes the concepts and usage of heavy load, rewriting, and several Java keywords. Summary very comprehensive http://blog.csdn.net/wangzihu/article/details/7527923


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.