"Internal class" Big Summary (Java), internal class summary java

Source: Internet
Author: User

"Internal class" Big Summary (Java), internal class summary java

(The documents collected a long time ago in this article (I just made typographical changes), author James, the link address is not found. Thank you, James)

 

Internal class location:

Internal classes can act in methods and external classes, and are called local internal classes in methods. Internal classes are divided into instance internal classes and static internal classes.

 

Class access modifiers for external and internal classes:

The external class can be public and default, and the internal class can be public, private, or protected.

 

Relationship between internal and external classes:

* In [instance internal class]

A: The internal class can access members of all access modifiers in the external class.

B: an external class instance corresponds to 0 or n internal class instances. Members of the internal class cannot be directly accessed in the external class. They must be accessed through the instance of the internal class.

 

* In [static internal class]

A: The static internal class can directly access the static members of the external class. If you access the instance members of the external class, you must access the members through the instance of the external class. When creating an internal class instance, you do not have to create an external class instance ..

B: The External class can directly access static members of the static internal class through the complete class name. to access non-static members of the static internal class, you must create an instance of the static internal class.

public class StaticInnerTest {      public static class A      {          public int a = 10;          static int b = 100;      }      public static void main(String[] args)      {            StaticInnerTest.A mya = new StaticInnerTest.A();             mya.a = 1234;            System.out.println(""+ mya.a);     }}

The above code can be run successfully and has been tested.

 

* In [local internal class]

A: The local internal class is the same as the instance internal class, and can access all members of the external class.

B: External classes do not know the existence of local internal classes, so they cannot be accessed.

 

 

Classification of internal classes:

1. Member internal class (instance internal class, static internal class)

2. Local internal class

 

(1) member internal class (class member)

* (1) instance internal class:

A. When creating an instance's internal class instance, the instance of the external class must already exist.

Outer. InnerTools its = new Out (). new InnerTools ();

The above code is equivalent:

Outer out = new Outer ();

Outer. InnerTools its = out. new InnerTools ();

 

(2) instances of the internal class of the Instance [automatically] Hold the reference of the instance of the external class, so in the internal class of the Instance

You can directly access [all] members of the external class (this refers to all public, protected, private, static methods and member variables in the external class)

The reason for access is that an internal class instance can be accessed only when an existing external class instance is needed in the internal class of the instance. See (1 ).

Outer. InnerTools its = new Outer (). newInnerTools ();

 

[Note:] in multiple nesting,The internal class of the instance can access members of all external classes.

Class A{        Private void methodA(){}        Class B        {              Private void methodB(){}              Class C              {                   Private void MethodC()                   {                         methodA();                         methodB();                   }                }         }}

 

(3) In the internal class of the instance, the instance of the external class has a one-to-many relationship with the instance of the internal class, and an internal class instance

Only one external class instance is referenced, and one external class instance corresponds to zero or n internal class instances. In the external class, [cannot] directly access members of the internal class, it must be accessed through an internal class instance.

Note: static members cannot be defined in the instance class.

 

 

 

* (2) static internal class

Class A{       Public static class B      {           Int v;      }} Class Test{    Public void test()   {        A.B b = new A.B();        b.v = 1;   }}

 

  1. The static internal class can directly access the static members of the external class. If you access the instance members of the external class, you must access it through the instance of the external class.

 

class A {    private int a1;    private static int a2;    public static class B  {     int b1 = a1;     int b2 = a2;     int b3 = new A().a1;  }}

 

  1. You can define static members and instance members in a static internal class.
 class A{      public static class B     {          int v1;          static int v2;          public static class C         {               static int v3;          }     }}

 

 

  1. The test class can directly access the static members of the static internal class through the complete class name.

 

class A{      public static class B      {            int v1;            static int v2;            public static class C            {                  static int v3;                  int v4;            }      }} public class Client{      public void test()      {            A.B b = new A.B();            A.B.C c = new A.B.C();            b.v1 = 1;            b.v2 = 1;            A.B.v1 = 1//error            A.B.v2 = 1;            A.B.C.v3 = 1;      }}

 

 

 

A local internal class is an internal class defined in a method. Its visible range is the current method. Like local variables, local internal classes cannot be modified using access modifiers (public, private, protected) or static. Local internal classes are characterized:

 

The local internal class can only be used in the current method. 

class A{       B b = new B();//error       public void method()      {            class B           {               int v1;               int v2;               class C              {                    int v3;              }           }          B b = new B();          B.C c = b.new C();     }}

 

The local internal class is the same as the instance internal class and cannot contain static members.

 

class A{        public void method()        {              class B             {                   static int v1;//error                   int v2;                   static class C //error                  {                      int v3;                  }           }      }}

 

 

Internal classes defined in local internal classes cannot be public protected, and private access modifiers (Local internal classes cannot be modified by public protected private access modifiers)

 

The local internal class is the same as the instance internal class. It can access all members of the external class. In addition, the local internal class can also access final type parameters and variables in the method in which the local internal class is located.

 

class A{        int a;        public void method(final int p1,int p2)       {            int localV1 = 1;            final int localV2 = 2;            class B           {              int b1 = a;              int b2 = p1;              int b3 = p2;//error              int b4 = localV1//error              int b5 = localV2;          }     }}

 

 

 

 

 

 

The anonymous internal class does not have a constructor, but it calls the constructor in the parent class.

Public class A {A (int y) {System. out. println ("not the default constructor");} A () {System. out. println ("default constructor");} void method () {System. out. println ("from A");} public static void main (String [] args) {// new (). method (); // default constructor, from A = new a () {void method () {System. out. println ("I am the method in the anonymous internal class");}/* That is, the anonymous constructor automatically calls the constructor in the parent class */. method (); // default constructor. I am the method in the anonymous internal class }}

 

(2) Although the anonymous internal class does not have a constructor, You can provide an instance initialization code in the anonymous internal class. the Java Virtual Machine will execute this code after calling the constructor of the parent class.

 

public static void main(String [] args) {     int v = 1;     A a = new A(v)    {         {           System.out.println("init instance");         }         void method()        {           System.out.println("from anonymous");        }       };     a.method(); }

 

The program execution result is as follows:

Another constructer // result of the constructor execution in the parent class

Init instance

From anonymous

 

Supplement:

 

 abstract class A   {          A a = new A()          {               void method()               {                    System.out.println("inner");                }          }          abstract void method();    }
  1. In addition to inheriting classes, anonymous internal classes can also implement interfaces. [Key]

 

Ccass Sample  {        public static void main(String [] args)       {          Thread t = new Thread(new Runnable()          {                public void run()               {                  for(int i = 0; i < 100; i++)                 {                      System.out.print(i);                 }               }          });       }   }
  1. The same as the local internal class, the anonymous internal class can access all members of the external class. If the anonymous internal class is located in a method, the final type variables and parameters of the method can also be accessed.

 

  1. The local internal class is the same as the anonymous internal class, and the name is invisible outside the method, so it can encapsulate the type name.

 

 

Anonymous internal classAndLocal internal classDifferences]

 

1. Less code for anonymous internal classes

 

2. A local internal class can have multiple overload constructor methods, and the test class can create instances of local internal classes multiple times. The anonymous internal class does not have to overload the constructor method, and can only be created once.

Therefore, if you only need to create an instance of an internal class, you can use an anonymous internal class to make the program code concise and clear. If you need to create an internal class instance multiple times, use a local internal class.

 

Internal class summary:

Author: James

References: <Core Java>


Java internal class

In java, there is a kind of class called inner class, also known as nested class, which is defined inside other classes. An internal class is a member of its external class. Like other members, it can directly access the data and methods of its external class. However, compared with external classes, only public and default modifiers are different. An internal class can be any modifier as a member. During compilation, the internal class name is OuterClass $ InnerClass. class.

1. Internal class Access Data Variables
In some cases, when the variables defined in the internal class are the same as those in the external class, how can we ensure correct access to every variable?

1.1 calling internal class methods directly from external classes in main

Class Outer
{
Private int index = 10;
Class Inner
{
Private int index = 20;
Void print ()
{
Int index = 30;
System. out. println (this); // the object created from the Inner
System. out. println (Outer. this); // the object created from the Outer
System. out. println (index); // output is 30
System. out. println (this. index); // output is 20
System. out. println (Outer. this. index); // output is 10
}
}

Void print ()
{
Inner inner = new Inner (); // get internal class reference
Inner. print ();
}
}

Class Test
{
Public static void main (String [] args)
{
Outer outer = new Outer ();
Outer. print ();
}
}
Here, the internal class Inner keyword this points to the internal class Inner object. to point to the external class object, you must add the external class name before the this pointer, indicates that this is the debris that points to the external class structure, such as Outer. this.

1.2 explicitly returning internal class references in main

Class Outer
{
Private int index = 10;
Class Inner
{
Private int index = 20;
Void print ()
{
Int index = 30;
System. out. println (index );
System. out. println (this. index );
System. out. println (Outer. this. index );
}
}

... The remaining full text>

Differences between static and internal classes in java

Like normal classes, internal classes can also be static. However, compared with non-static internal classes, the difference is that static internal classes do not point to external references. This is actually very similar to the nested classes in C ++. The biggest difference between Java internal classes and C ++ Nested classes is whether there is a reference pointing to the outside, of course, there are still differences from the design perspective and some details.

In addition, no non-static internal class can have static data, static methods, or another static internal class (internal class nesting can be more than one layer ). However, static internal classes can have all of this.

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.