Java detailed anonymous inner class __java

Source: Internet
Author: User
I. Using anonymous inner class inner class

Anonymous inner classes are somewhat strange to create because they do not have a name. Create the following format:

New parent class Constructor (parameter list) | Implement Interface ()  
    {  
     //anonymous inner class part  
    }

Here we see that using anonymous inner classes we have to inherit a parent class or implement an interface, and of course we can only inherit a parent class or implement an interface. It also has no class keyword, because an anonymous inner class is a reference that uses new to generate an object directly. Of course, the 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 () + "able to 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:
geese can fly 10000 meters

In the test class, the test () method takes an argument of a bird type, and we know that an abstract class is not directly new, and we have to have an implementation class before it can be new to its implementation class instance. Therefore, the anonymous inner class is used directly in the Mian method to create a bird instance.

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

For this anonymous inner class code can actually 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, which transitions to a reference to the bird type.

There is a flaw in the use of anonymous inner classes, which is that it can only be used once, creating an anonymous inner class that immediately creates an instance of the class whose definition disappears immediately, so that anonymous inner classes cannot be reused. For the above example, if we need to use the inner class in the test () method more than once, we recommend that you redefine the class instead of using an anonymous inner class. ii. Matters of note

In the process of using anonymous inner classes, we need to look at the following points:

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

2, the anonymous inner class is not allowed to define constructors.

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 restrictions on the local inner class are also valid for anonymous inner classes.

5. An anonymous inner class cannot be abstract, and it must implement all the abstract methods of the inherited class or implemented interface. third, the use of the formal parameters why to be final

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

When we pass an argument to an anonymous inner class, if the parameter is to be used in the inner class, then the formal parameter must be final. That is, the formal parameter must be final when the formal parameter of the method in which it is used is required by the inner class.

Why do we have to be final?

First of all, we know that after the internal class compiles successfully, it produces a class file that is not the same class file as the external class, and simply keeps a reference to the outer class. When the arguments passed in by an outer class need to be called by an inner class, they are 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 code above, it looks as if the name parameter should be called directly by an inner class. Actually, after the Java compilation, the actual operations are 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. Innerclass$name + "----" + this. innerclass$age);
    }

So from the code above, the inner class is not a direct call to the arguments passed by the method, but instead uses its own constructor to back up the incoming arguments, and instead of the arguments passed in by the external method, its own internal method invocation actually has its own properties.

Until there is no explanation as to why final. The properties in an inner class and the parameters of an external method both look the same thing from the outside, but they are not, so they can be changed arbitrarily, which means that in the inner class my changes to the attributes do not affect the external parameters, but this is not feasible from a programmer's point of view. After all, standing in the process of the point of view of these two is the same, if the internal class should be changed, and the external method of the formal parameters are not changed this is difficult to understand and unacceptable, so in order to maintain the consistency of the parameters, it is required to use final to avoid the formal parameter unchanged

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

So 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 anonymous inner classes do not have constructors. So how do you initialize an anonymous inner class? Use the construction code block. The effect of creating a constructor for an anonymous inner class can be achieved by using a constructed code block.

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 {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 ("Chenssy");
    System.out.println (Inner_2.getname ()); }
}
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.

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.