Java internal classes and usage scenarios

Source: Internet
Author: User

The so-called inner class, which is the class defined in another class. So why is there a concept of inner class, and what is his usage scenario?
First, take a look at the characteristics of the inner class:

1. It embodies a code hiding mechanism and access control mechanism, the internal class and the external class has a certain relationship, often only the external class calls this inner class, so there is no need to specifically use a Java file to store this class.

Class Outer {int private class Inner {int num; }}

The generic class is not allowed with the private modifier, but the inner class can, in that instance, class inner only visible to outer, other classes inaccessible to the inner class.

Note that there is an exception to this, and if the access modifier for the inner class is set to public, it can be used by other classes, but the inner class must be instantiated through an external class.

 public class Outer {private int num = 1 public class Inner { Span style= "color: #0000ff;" >private int num = 2public static void< Span style= "color: #000000;" > main (string[] args) {Outer Outer = new Outer (); Inner Inner = outer. new Inner (); System.out.println (Inner.num); }} 

2. It contains a this pointer to the external class, which allows access to all elements of the outer classes, including members and methods of all public/private

 Public classOuter {Private intnum = 1;  Public classInner {Private intnum = 2; Private voidfunc () {System.out.println (Outer. This. Num); }    }     Public Static voidMain (string[] args) {Outer Outer=NewOuter (); Inner Inner= Outer.NewInner ();    Inner.func (); }}

On the other hand, the external class also has access to all elements of the inner class, including private members and methods of the inner class, in reverse:

 Public classOuter {Private intnum = 1;  Public classInner {Private intnum = 2; }     Public voidfunc () {Inner Inner=NewInner ();    System.out.println (Inner.num); }     Public Static voidMain (string[] args) {Outer Outer=NewOuter ();    Outer.func (); 2}}

Classification:

First, members of the internal class

When a class is not used by another class except his external class, the member inner class is used. In this case, the inner class is attached to an external class and may exist for the following reasons: 1. It is not possible for other classes to use this inner class. 2. The inner class cannot be used by other classes and may cause errors. This is a scenario where the inner class uses more than one.

1) The outer class can access the members and methods of the inner class directly, but you must first create an object of an inner class, and then use its members and methods through that object.

2) Inner classes can access members and methods of external classes, but be aware that when an inner class has the same members or methods as the outer class, a hidden behavior occurs, and by default, members of the members ' inner classes are accessed. If you want to access a member of the same name as an external class, you need to access the following form: External class. This. Member variable/method

3) The inner class is just a compile-time concept, and once the compilation succeeds, it becomes a completely different two class. For an external class named Outer and its internally defined inner class named Inner, the Outer.class and Outer$inner.class two classes are generated after compilation

4) member inner classes are no different from ordinary members, and can be modified and restricted as normal members.

 Public classOuter {Private intnum = 1; Private intNUM1 = 10;  Public classInner {Private intnum = 2;  Public voidfunc () {System.out.println (Outer. This. Num);        System.out.println (NUM1); }    }     Public Static voidMain (string[] args) {Outer Outer=NewOuter (); Inner Inner= Outer.NewInner ();    Inner.func (); }}

Second, local internal class

A local inner class is a class that is defined within a method or scope, and differs from a member's inner class in that the access of a local inner class is limited to within a method or within that scope. Local inner classes, like local variables inside a method, cannot have public, protected, private, and static modifiers.

 Public classOuter {Private intnum = 1; Private intNUM1 = 10;  Public voidfunc () {classInner {Private intnum = 2; } Inner Inner=NewInner ();    System.out.println (Inner.num); }     Public Static voidMain (string[] args) {Outer Outer=NewOuter ();    Outer.func (); }}

Third, static internal class

A static inner class is also a class that is defined in another class, except that there is a keyword static in front of the class. A static inner class is not required to rely on an external class, it does not hold a reference to an external class object, and it cannot use a non-static member or method of an external class, because in the absence of an object of an outer class, you can create an object of the static inner class. If you allow access to non-static members of an external class, there is a contradiction because the non-static members of the outer class must be attached to the concrete object. Its only function is as the class is loaded, not as the object is created.

 Public class Outer {    staticclass  Inner {        public  Inner () {        }    }      Public Static void Main (string[] args) {        new  Outer.Inner ();}    }

Iv. Anonymous Internal classes

The

Anonymous inner class should be the most commonly used when writing code, and anonymous internal classes are not only convenient when writing code for event listening, but also make the code easier to maintain. Anonymous inner classes are the only classes that do not have constructors. Because it does not have a constructor, the use of anonymous internal classes is very limited, and most anonymous inner classes are used for interface callbacks. Anonymous inner classes are automatically named Outer$1.class by the system at compile time. In general, anonymous internal classes are used to integrate other classes or implement interfaces, and there is no need to add additional methods, just the implementation of integration methods or overrides.

 Public class Outer {    publicvoid  func () {        System.out.println ("1");    }      Public Static void Main (string[] args) {        new  Outer () {            publicvoid func () {                System.out.println ("2");            }        };        Inner.func ();    }}


Summarize:

1. Each inner class can integrate an implementation of an interface independently, so no matter whether an external class has integrated an (interface) implementation, there is no effect on the inner class. Internal classes make multi-integrated solutions complete.

2. To facilitate the existence of a certain logical relationship of the classes organized together, but also can be hidden from the outside world.

3. Easy to write time drivers.

4. Easy to write thread code.

Java internal classes and usage scenarios

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.