Java anonymous inner class & inner class

Source: Internet
Author: User
Tags event listener static class thread class

The difference between inner class and anonymous inner class in Java

inner class: The inner class can be static or non-static, static and static class variables can only be included, only static elements of the outer class can be accessed, and inner classes may be instantiated and used multiple times.

anonymous inner class: It can only be used once, without distinguishing between static and non-static. If a variable of an external class is used, it must be a class variable or an instance variable, that is, a class-defined variable, or a final local variable. Anonymous inner class If you inherit a class, you can override the method of that class, just like the normal inner class.

Summary: You can replace the inner class with an anonymous inner class, but the anonymous inner class encoding is very concise and easy to read, unless you need to use that inner class more than once, or we recommend using an anonymous inner class.

Second, the use of the internal class time

1, when the implementation of the event listener (for example, ActionListener ... The use of internal classes is easy to achieve);

2, when writing event-driven (the object of the inner class can access the member methods and variables of the external class, note including private members);

3, in the case of the function can be achieved, in order to save the compilation of the resulting bytecode (internal classes can reduce the bytecode file, that is, the Java file compiled by the. class file);

Third, the use of anonymous internal class time

An anonymous inner class is a special case of an inner class. It has only one instance, and there is no reference. Therefore, it is generally implemented in an internal class, but the instance is used only once (which can reduce resource overhead);

===========================================================================

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

1. Basic implementation of anonymous inner classes
Abstract classPerson { Public Abstract voideat ();}  Public classDemo { Public Static voidMain (string[] args) {person P=NewPerson () { Public voideat () {System.out.println ("Eat Something");        }        };    P.eat (); }}

running result:eat something

As you can see, we directly implement the methods in the abstract class person in curly braces.

This allows you to omit the writing of a class

Also, anonymous inner classes can be used on interfaces

2. Using anonymous inner classes on the interface
 interface   person { public   void   Eat ();}  public  class   Demo { public  static  void   main (string[] args) {person P  = new   person () { public  void   eat () {System.out.println (" Eat Something ");        }        };    P.eat (); }}

running result:eat something

As can be seen from the above example, as long as a class is abstract or an interface, the methods in its subclasses can be implemented using anonymous inner classes

The most common situation is in the implementation of multithreading, because to implement multithreading must inherit the thread class or inherit the Runnable interface

anonymous inner class implementations of the 3.Thread class
 public  class   Demo { public  static  void   main (string[] args) {Thread t  = new   Thread () { public  void   run () { for  (int  i = 1; I <= 5;                I++ + "" 

operating Result:1 2 3 4 5

Anonymous inner class implementation of the 4.Runnable interface
 Public classDemo { Public Static voidMain (string[] args) {Runnable R=NewRunnable () { Public voidrun () { for(inti = 1; I <= 5; i++) {System.out.print (i+ " ");        }            }        }; Thread T=NewThread (R);    T.start (); }}

operating Result:1 2 3 4 5

The following are the inner classes

Example 1: The basic structure of an inner class

//External ClassclassOut {Private intAge = 12; //Inner class    classIn { Public voidprint () {System.out.println (age); }    }}  Public classDemo { Public Static voidMain (string[] args) {out.in in=NewOut ().NewIn ();        In.print (); //or access by sowing        /*out = new Out ();        Out.in in = Out.new in ();        In.print (); */    }}

Run Result:12

From the above example, it is not difficult to see that the inner class actually seriously destroys the good code structure, but why use the inner class?

Because inner classes are free to use member variables of external classes (including private ones) without generating objects of external classes, this is the only advantage of inner classes

Like the heart can directly access the body's blood, rather than through the doctor to draw the blood

Example 2: Static inner class
classOut {Private Static intAge = 12; Static classIn { Public voidprint () {System.out.println (age); }    }}  Public classDemo { Public Static voidMain (string[] args) {out.in in=Newout.in ();    In.print (); }}

Run Result:12

As you can see, if you statically internal static, the inner class can only access static member variables of the outer class, with limitations

Second, because the inner class is statically, the out.in can be viewed as a whole, and can be directly new to the object of the inner class (access to static through the class name, it doesn't matter if the external class object is generated)

Example 3: Method Inner class
classOut {Private intAge = 12;  Public voidPrint (Final intx) {classIn { Public voidInprint () {System.out.println (x);            System.out.println (age); }        }        NewIn (). Inprint (); }}  Public classDemo { Public Static voidMain (string[] args) {out-out=Newout (); Out. Print (3); }}

Operation Result:

3
12

In the above code, we move the inner class into the method of the outer class, and then regenerate it into an inner class object in the method of the outer class to invoke the inner class method

If we need to pass in a parameter to a method in the outer class at this point, then the method parameter of the outer classes must use the final definition

As for final, there's no special meaning here, it's just a representation.

Java anonymous inner class & 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.

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.