Java Anonymous Inner class

Source: Internet
Author: User
Tags java anonymous class

Java Anonymous Inner class

An article in front of the anonymous inner class made a simple understanding, http://my.oschina.net/xinxingegeya/blog/297004. This article for an in-depth look at the use of anonymous internal classes


This in the Java anonymous class

The anonymous class feature of Ava is that a type can be implemented inline in the project, inheriting an existing concrete or abstract class, implementing an interface, and providing a complete member implementation. For example, here is an abstract class that defines an abstract method:

Javaabstract class Myabstractclass {String getName () {return ' Myabstractclass '; } abstract void print ();}

Then we use an anonymous class in another place, inheriting this class:

Javaclass MyClass {String getName () {return ' MyClass ';                } myabstractclass SomeMethod () {return new Myabstractclass () {public void print () {            System.out.println (GetName ());    }        }; }}

OK, now to ask a question, run the following line of code will print out what results?

Javanew MyClass (). SomeMethod (). print ();

the output is myabstractclass instead of MyClass. In other words, the GetName method that is called in an anonymous type is defined in Myabstractclass instead of the GetName method defined in the lexical scope (Lexical scope). According to the Java specification, this in the anonymous class (including the "implicit" this in the preceding code) represents the type itself object, regardless of the context. If you want to access the GetName method in the lexical scope (that is, the MyClass method), you must explicitly specify the MyClass class   , for example:

Javaclass MyClass {String getName () {return ' MyClass ';                } myabstractclass SomeMethod () {return new Myabstractclass () {public void print () {            System.out.println (MyClass.this.getName ());    }        }; }}


Anonymous inner class definition attribute field

The following is an example of an anonymous inner class,

package com.usoft.java;/** */public  Interface callback {    void call ();} 
package com.usoft.java;/** *  @author:  lenovo (2015-08-09 16:00)  */public  class test {    private final integer c = 12;     private Integer a;    private Integer b;     public test (integer a, integer b)  {         this.a = a;        this.b = b;     }    public static void main (String args[])  {         test test = new test (1, 2);         test.test (True);    }     Public void hello (Callback back)  {         Back.call ();     }&Nbsp;   public void test (Final boolean flag)  {         SYSTEM.OUT.PRINTLN ("test");         hello (new  callback ()  {            private  Integer ia = a;            private  integer ib = b;            @ Override            public void call ()  {                 System.out.println ("callback");                 if  (flag)                   &nBsp;  system.out.println (ia + ib + c);                 else                     system.out.println (Ia + ib  + C + 1);            }         });     }}

Anonymous inner classes, although anonymous, are also named after compilation. Look at the inverse of the anonymous inner class, the name of the class is test$1, and the normal class is no different.

C:\workspace5-gitosc\scala-sample\out\production\scala-sample\com\usoft\java>javap-p Test$1.classCompiled  From "Test.java" class Com.usoft.java.test$1 implements Com.usoft.java.CallBack {private Java.lang.Integer ia;  Private Java.lang.Integer IB;  Final Boolean Val$flag;  Final Com.usoft.java.Test this$0;  Com.usoft.java.test$1 (Com.usoft.java.Test, Boolean); public void call ();

two properties are defined in an anonymous inner class the initialization and assignment of IA and Ib,ia and IB is done in the constructor of the anonymous inner class, and the value is a and b in the outer class. an external variable flag was used in the anonymous inner class.

Where the initialization and assignment of IA and IB is more pronounced and better understood by the notation,

Public void test (Final boolean flag)  {    system.out.println (" Test ");     hello (New callback ()  {         private Integer ia = Test.this.a;         private integer ib = test.this.b;         @Override         public void call ()  {             system.out.println ("callback");             if  (flag)                  system.out.println (ia + ib + c);             else             &nbSp;   system.out.println (ia + ib + c + 1);         }    });}

Run the results,

Test

Callback

15


Initialization of an anonymous inner class

Since the anonymous inner class does not have a constructor (you can tell by deserializing that there is a constructor), then how to initialize the anonymous inner class, here is a method,

Public void test (Final boolean flag)  {    system.out.println (" Test ");     hello (New callback ()  {         private Integer ia = Test.this.a;         private integer ib = test.this.b;        {             ia = 3;             ib = 4;         }         @Override          public void call ()  {             system.out.println ("callback");             if  (flag)                  system.out.println (Ia + ib  + C);            else                 system.out.println (ia +  IB + C + 1);        }     });}

Through the code block, you can initialize the properties of the class, printing the result is 19;


Why use Final

With the result of the anti-compilation above, we can see that there is an external class parameter in the constructor (bytecode level) of the inner class, while the inner class has a reference to an outer class, and when the property of the outer class is used, the corresponding property value is obtained by reference to the external class. If the property reference of an external class changes, then the inner class and the outer class state are not unified. So for the sake of unity of state, all the attributes of the outer class are defined as final, that is, the immutable reference.

Private final Integer C = 12; Must be final


Summary of the use of anonymous internal classes
  1. When using an anonymous inner class, we must either inherit a class or implement an interface, but not both, and only inherit one class or implement an interface.

  2. In an anonymous inner class, a constructor cannot be defined.

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

  4. The anonymous inner class is a local inner class, so all restrictions on 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.

Reference: http://www.cnblogs.com/chenssy/p/3390871.html

Http://blog.zhaojie.me/2011/06/java-anonymous-method-closure-scope-this.html

=======================end=======================

Java Anonymous Inner class

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.