Java Learning Note 26 in-depth understanding of the Java anonymous inner class

Source: Internet
Author: User

A simple introduction to anonymous inner classes in the Java Learning Note 25 Preliminary cognitive Java class, but there are a lot of 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 (argument list) | Implement Interface ()      {       // Anonymous inner 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.

1  Public Abstract classBird {2     PrivateString name;3 4      PublicString GetName () {5         returnname;6     }7 8      Public voidsetName (String name) {9          This. Name =name;Ten     } One      A      Public Abstract intfly (); - } -  the  Public classTest { -      -      Public voidTest (Bird Bird) { -System.out.println (Bird.getname () + "able to fly" + () + "M"); +     } -      +      Public Static voidMain (string[] args) { ATest test =NewTest (); atTest.test (NewBird () { -              -              Public intFly () { -                 return10000; -             } -              in              PublicString GetName () { -                 returnGeese; to             } +         }); -     } the } *------------------ $ Output:Panax NotoginsengGeese 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:

1  Public classWildgooseextendsbird{2      Public intFly () {3         return10000;4     }5     6      PublicString GetName () {7         returnGeese;8     }9 }Ten  OneWildgoose Wildgoose =Newwildgoose (); ATest.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:

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:

1  Public classOuterclass {2      Public voidDisplayFinalString name,string Age) {3         classinnerclass{4             voiddisplay () {5 System.out.println (name);6             }7         }8     }9}

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:

1  Public classOuterclass$innerclass {2      PublicInnerclass (String name,string age) {3          This. Innerclass$name =name;4          This. Innerclass$age =Age ;5     }6     7     8      Public voiddisplay () {9System.out.println ( This. Innerclass$name + "----" + This. Innerclass$age);Ten     } One}

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.

1  Public classOutclass {2      PublicInnerclass Getinnerclass (Final intAgeFinalString name) {3         return NewInnerclass () {4             intAge_;5 String name_;6             //building blocks of code to complete initialization work7             {8                 if(0 < Age && Age < 200){9Age_ =Age ;TenName_ =name; One                 } A             } -              PublicString GetName () { -                 returnname_; the             } -              -              Public intGetage () { -                 returnAge_; +             } -         }; +     } A      at      Public Static voidMain (string[] args) { -Outclass out =Newoutclass (); -          -Innerclass inner_1 = Out.getinnerclass (201, "Chenssy"); - System.out.println (Inner_1.getname ()); -          inInnerclass inner_2 = Out.getinnerclass (, "Chenssy"); - System.out.println (Inner_2.getname ()); to     } +}

Java Learning Note 26 in-depth understanding of the Java 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: 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.