"50" Java Anonymous inner class anatomy

Source: Internet
Author: User

Anonymous Inner class Description:

Anonymous inner class is also an inner class without a name

Because there is no name, the anonymous inner class can only be used once, and it is often used to simplify code writing

But there is also a precondition for using anonymous inner classes: You must inherit from a parent class or implement an interface

The declaration format of an anonymous inner class is as follows:

new ParentName(){...// 内部类的定义}
Usage scenarios for anonymous inner classes:

. Only one instance of the class is used.
• The class is used immediately after the definition.
• The class is very small (sun recommended is below 4 lines of code)
• Naming a class does not make your code easier to understand.

The use principle of anonymous inner classes:

• Anonymous inner classes cannot have a constructor method.
• Anonymous inner classes cannot define any static members, static methods.
• Anonymous inner class cannot be public,protected,private,static.
• Only one instance of an anonymous inner class can be created.
• An anonymous inner class must be behind new, implementing an interface with its implication or implementing a class.
• Because the anonymous inner class is a local inner class, all restrictions on the local inner class are applied to it.

Centralized usage of anonymous inner classes: A, an inherited anonymous inner class
publicclass Car {publicvoiddrive(){System.out.println("Driving a car!");}publicstaticvoidmainnew Car(){publicvoiddrive() {System.out.println("Driving another car!");}};car.drive();}}结果输出了:Driving another car! Car引用变量不是引用Car对象,而是Car匿名子类的对象。
B, an anonymous internal class of interfaces.
interface Vehicle {publicvoiddrive();}class Test{publicstaticvoidmainnew Vehicle(){publicvoiddrive(){System.out.println("Driving a car!");}};v.drive();}}上面的代码很怪,好像是在实例化一个接口。事实并非如此,接口式的匿名内部类是实现了一个接口的匿名类。而且只能实现一个接口。
C, an anonymous inner class of parameters.
class Bar{void doStuff(Foo f){f.foo();}}interface Foo{void foo();}class Test{staticvoidnew Bar();b.doStuff(new Foo(){publicvoid foo(){System.out.println("foofy");}});}}
Precautions

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.

Why is the formal parameter used to be final:

"This is a compiler design problem and it's easy to understand if you understand how Java is compiled.
First, when the inner class is compiled, it generates a separate inner class of the. class file, which is not in the same class file as the external class.

 Public void Dosome(FinalString A,Final intb) {class dosome{ Public void Dosome() {System.out.println (a+b)}}; Dosome some=NewDosome ();  Some.dosome (); The code looks like the A and B arguments that are called directly from the inner class, but it's not, actually, after the Java compiler compiles the actual operation code is class outer$dosome{ Public Dosome(FinalString A,Final intb) { This. Dosome$a=a; This.  Dosome$b=b; } Public void Dosome() {System.out.println ( This. dosome$a+ This.  DOSOME$B); }  }}

An inner class is not a parameter that is called directly by a method, but rather an inner class that backs up the arguments passed in by its own constructor to its own interior, and its own internal method call is actually its own property rather than the parameters of the external class method.
This makes it easy to figure out why you should use final, because both look the same thing from the outside, and if the inner classes get rid of the values of these parameters, it is not possible to affect the original parameters, but this loses the consistency of the parameters, because from the programmer's point of view they are the same thing, If the programmer in the design of the internal class to break the value of the parameter, but the external call and found that the value has not been broken, it is very difficult to understand and accept, in order to avoid this embarrassing problem exists, So the compiler designer sets the parameters that internal classes can use to be final to avoid the existence of this inexplicable error. ”

(The simple understanding is that copy references, in order to avoid changes in the reference value, such as by the external class method modification, etc., resulting in inconsistent values of the inner class, so that the reference is not changed with final) anonymous inner 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 classoutclass { PublicInnerclassGetinnerclass(FinalintAge,final String name) {return NewInnerclass () {intAge_; String name_;//Construct code block to complete initialization work{if(0< Age && Age < ${Age_ = age;                name_ = name; }            } PublicStringGetName() {returnname_; } Public int Getage() {returnAge_;    }        }; } Public Static void Main(string[] args) {Outclass out=NewOutclass (); 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 ()); }}
Welcome to the group: public number It face questions summary discussion group

If the scan does not go in, add me (rdst6029930) pull you. Sweep my QR code plus me

You are welcome to pay attention to the "It question summary" subscription number. Every day to push the classic face test and interview tips, are dry! The QR code of the subscription number is as follows:

Reference:
Http://baike.baidu.com/view/7942850.htm
http://android.blog.51cto.com/268543/384844
Http://www.cnblogs.com/chenssy/p/3390871.html
Http://www.cnblogs.com/nerxious/archive/2013/01/25/2876489.html

"50" Java Anonymous inner class anatomy

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.