Inner class and anonymous inner class

Source: Internet
Author: User

Inner class: One class is defined in another class

1  Public class A {23      Public class b{4         5     }6 }

Here, B is an inner class, and a is its corresponding outer class.

1. B You can use member variables and functions in a, but do not represent owning them, unlike inheritance.

2. Generate B$a.class class after compiling.

3. You can declare an inner class as static. A static inner class can be accessed using the name of the external class. A static class cannot access a non-static member of an external class.

4. Generation of inner class objects:

Non-static:

Outerclass.innerclass InnerObject = Outobject. New Innerclass ()  

Static:

New Outobject.innerclass ()   

Anonymous inner class: An inner class without a name.

New B (); B.fun (new  A () {    publicvoid  print () {        System.out.println ("Anonymous inner class");    });

1. Anonymous inner classes must extend the parent class or implement an interface.

2. The anonymous inner class is compiled into a class named Outerclassname$n.class. For example, if the external class test has two anonymous classes, they are compiled into Test$1.class and Test$2.class.

3. The formal parameter must be final when the formal parameter of the method is used inside the inner class.

   Public Inner Getinner (final  string name, String city) {         returnnew  Inner () {             /c7>Private String nameStr = name;                Public String GetName () {                 return  nameStr;             }         };     }

Why should it be defined as final? There are similar explanations on the Internet:

"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.

When an external class is called by an inner class, it is called directly from the Java program's point of view, for example:

public void Dosome (final String a,final int b) {

Class Dosome{public void Dosome () {System.out.println (a+b)}};

Dosome some=new dosome ();

Some.dosome ();

}

From the code it looks like the A and B parameters that are called directly from the inner class, but actually not, after the Java compiler compiles the actual operation code is

Class outer$dosome{

Public Dosome (final String a,final int b) {

This. Dosome$a=a;

This. Dosome$b=b;

}

public void Dosome () {

System.out.println (this. Dosome$a+this. DOSOME$B);

}

}}

From the above code, the inner class is not directly called by the method to pass in the parameters, but the internal class will pass in the parameters through their own constructor back to their own internal, the internal method calls the actual property of its own 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. ”

4. Anonymous inner class implementation of thread class

 Public class Demo {    publicstaticvoid  main (string[] args) {        new Thread () {            publicvoid  run () {                for (int  i = 1; I <= 5; i++) {                    + "");}}        ;        T.start ();    }}
Operating Result: 1 2 3 4 5

5. Anonymous inner class implementation of 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

Inner class and 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.