"Go" Java Improvement Chapter (10)-----Details anonymous inner class

Source: Internet
Author: User

Label:

Original URL: http://www.cnblogs.com/chenssy/p/3390871.html

A brief introduction to the anonymous inner class is made in the Java improvement-----, but there are many other details in the inner class, so this blog is derived. In this blog you can learn about the use of anonymous internal classes, what to note about anonymous inner classes, how to initialize anonymous inner classes, and why the formal parameters used by anonymous inner classes are final.

First, use anonymous inner class inner class

Anonymous inner class because there is no name, it is created in a somewhat strange way. The creation format is as follows:

New parent class Constructor (parameter list) | Implements interface ()      {       ///Anonymous Inner class class body part      }

Here we see the use of anonymous inner classes we have to inherit a parent class or implement an interface, and of course only inherit one parent class or implement an interface. It also does not have the class keyword, because the anonymous inner class is a reference that uses new directly to generate an object. Of course, this reference is implicit.

Public abstract class Bird {    private String name;    Public String GetName () {        return name;    }    public void SetName (String name) {        this.name = name;    }        public abstract int Fly ();} public class Test {public        void Test (Bird Bird) {        System.out.println (bird.getname () + "can Fly" + bird.fly () + "M"); 
   } public        static void Main (string[] args) {        test test = new test ();        Test.test (New Bird () {public                        int fly () {                return 10000;            }                        Public String GetName () {                return "wild Goose";            }}        );    } ------------------Output: Wild goose can fly 10000 meters

In the test class, the test () method accepts a parameter of type bird, and we know that there is no way for an abstract class to be directly new, we must first have an implementation class in order to new out of its implementation class instance. Therefore, the anonymous inner class is used directly in the Mian method to create an bird instance.

Because an anonymous inner class cannot be an abstract class, it must implement its abstract parent class or all the abstract methods inside the interface.

For this anonymous inner class code can be split into the following form:

public class Wildgoose extends bird{public    int Fly () {        return 10000;    }        Public String GetName () {        return "wild Goose";    }} Wildgoose wildgoose = new Wildgoose (); Test.test (Wildgoose);

Here the system creates an object that inherits from the anonymous class of the bird class and transforms it into a reference to the bird type.

There is a flaw in the use of anonymous inner classes, that is, it can only be used once, when an anonymous inner class is created, it immediately creates an instance of the class, and the definition of the class disappears immediately, so the anonymous inner class cannot be reused. For the above example, if we need to use multiple internal classes within the test () method, it is recommended that you redefine the class instead of using an anonymous inner class.

Second, the matters needing attention

In the process of using anonymous inner classes, we need to pay attention to the following points:

1 . When using anonymous inner classes, we must inherit a class or implement an interface, but both cannot be combined, and can inherit only one class or implement an interface.

2 . The constructor cannot be defined in an anonymous inner class.

3 . No static member variables and static methods can exist in the anonymous inner class.

4 . The anonymous inner class is a local inner class, so all the limitations of the local inner class also take effect on the anonymous inner class.

5 . An anonymous inner class cannot be abstract, it must implement all the abstract methods of an inherited class or an implemented interface.

Iii. why the formal parameters used are final

Reference documents: http://android.blog.51cto.com/268543/384844

When we pass parameters to an anonymous inner class, the formal parameter must be final if it needs to be used in the inner class. That is , the parameter must be final when the formal parameter of the method is used inside the inner class.

Why does it have to be final?

First we know that after the internal class is successfully compiled, it produces a class file that is not the same class file as the external class, and only retains references to external classes. When an external class passes in a parameter that needs to be called by an inner class, it is called directly from the Java program's point of view:

public class Outerclass {public    void display (final String name,string age) {        class innerclass{            void Display ( {                System.out.println (name);}}}}    

From the above code, it seems that the name parameter should be called directly by the inner class. In fact, after the Java compilation, the actual operation is as follows:

public class Outerclass$innerclass {public    innerclass (String name,string age) {this        . Innerclass$name = name;        This. Innerclass$age = age;    }            public void display () {        System.out.println (this. Innerclass$name + "----" + this. innerclass$age);}    }

Therefore, from the above code, the inner class is not directly invoke the parameters passed by the method, but instead uses its own constructor to back up the parameters passed in, its own internal method calls the actual time its own property rather than the external method passed in the parameters.

Until there's no explanation why it's final? The properties in the inner class and the parameters of the external method both look the same thing from the outside, but they are not, so they can be arbitrarily changed, that is, in the inner class my change to the property does not affect the external parameter, but this is not feasible from the programmer's point of view, After all, from the point of view of the program, these two are the same, if the inner class is changed, and the external method's parameters are not changed this is difficult to understand and unacceptable, so in order to maintain the consistency of the parameter, it is necessary to use final to avoid the formal parameter unchanged.

The simple understanding is that a copy reference, in order to avoid the reference value changes, such as by the external class method modification, and so on, resulting in the internal class resulting in inconsistent values, so use final to make the reference immutable.

Therefore, if an anonymous inner class is defined and you want it to use an externally defined parameter, the compiler will require that the parameter reference be final.

Iv. Anonymous Internal class initialization

We generally use constructors to do the initialization of an instance, but the anonymous inner class is not a constructor! So how do you initialize an anonymous inner class? Use Construction code blocks! The effect of creating a constructor for an anonymous inner class can be achieved by constructing a block of code.

public class Outclass {public    innerclass getinnerclass (final int age,final String name) {        return new Innerclass () {            int age_;            String name_;            Constructs a block of code to complete initialization work            {                if (0 < Age && Age < $) {                    Age_ = age;                    name_ = name;                }            }            Public String GetName () {                return name_;            }                        public int getage () {                return age_;            }        };    }        public static void Main (string[] args) {        outclass-out = new Outclass ();                Innerclass inner_1 = Out.getinnerclass (201, "Chenssy");        System.out.println (Inner_1.getname ());                Innerclass inner_2 = Out.getinnerclass (at "Chenssy");        System.out.println (Inner_2.getname ());}    }

Consolidate the foundation, raise the technology, do not fear the difficulty, climb the peak!!!!!!

PS: If you think the article is helpful to you, do not forget to recommend or share, because your support, is I continue to write the power and source of the next chapter!

Chenssy
Source: http://www.cnblogs.com/chenssy/
This article is copyright to the author and the blog Park, Welcome to reprint, but without the consent of the author must retain this paragraph, and in the article page obvious location to the original link, otherwise reserves the right to pursue legal responsibility.

"Go" Java Improvement Chapter (10)-----Details anonymous inner class

Related Article

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.

Tags Index: