Java internal class (InnerClass) ---- non-static internal class, static internal class, local internal class, anonymous internal class

Source: Internet
Author: User

Java internal class (InnerClass) ---- non-static internal class, static internal class, local internal class, anonymous internal class
Many people are not familiar with the java underwear Class. In fact, similar concepts also exist in c ++, that is, the Nested Class. What are the differences between these two classes, the following is a comparison. On the surface, the internal class defines a class in the class (as we can see below, the internal class can be defined in many places), but it is actually not that simple, at first glance, the internal class seems a little redundant. His use may not be so significant for beginners, but with his deep understanding, you will find that java designers have a great deal of effort in the underwear category. Learning to use internal classes is part of advanced java programming. It allows you to design your program structure more elegantly. The following describes the first meeting: copy the public class TestInnerClass {public static void main (String args []) {Goods good = new Goods (); contents content = good. dest (); System. out. println (content. value (); Destination destination = good. cont ("BeiJing"); System. out. println (destination. readLabel () ;}} interface Contents {int value ();} interface Destination {String readLabel ();} class Goods {private class Content implem Ents Contents {private int I = 11; public int value () {return I ;}} protected class GDestination implements Destination {private String label; private GDestination (String whereTo) {label = whereTo;} public String readLabel () {return label;} public Content dest () {return new Content ();} public GDestination cont (String s) {return new GDestination (s) ;}} in this example, class Content and GDestination are defined in Goo The ds class has private and protected modifiers to control the access level. Content represents Goods Content, while GDestination represents Goods destination. In the following main () method, you can use Contents content and Destination destination to perform operations. You have never even seen the names of these two internal classes, the benefits of internal classes are embodied, hiding the operations you don't want others to know, that is, encapsulation. At the same time, we also found that the first method to get internal class objects out of the scope of the external class is to create and return using its external class method. In the preceding example, the dest () and cont () methods do this. So, is there any other way? Of course, the syntax format is as follows: OuterClass outerObject = new OuterClass (Constructor parameters); OuterClass. innerClass innerObject = outerObject. new InnerClass (Constructor parameters); // Of course, at this time, we should change the number of lines of the internal class to public, not private. Note that when creating a non-static internal class object, you must first create an external class object. As for the reason, it will lead to our next topic that non-static internal class objects have references pointing to their external class objects. I will slightly modify the example just now: copy the public class TestInnerClass {public static void main (String args []) {Goods good = new Goods (); Contents content = good. dest (); System. out. println (content. value () ;}} interface Contents {int value ();} interface Destination {String readLabel ();} class Goods {private int valueRate = 2; private class Content implements Contents {private int I = 11 * ValueRate; public int value () {return I;} protected class GDestination implements Destination {private String label; public GDestination (String whereTo) {label = whereTo ;} public String readLabel () {return label;} public Content dest () {return new Content ();} public GDestination cont (String s) {return new GDestination (s) ;}} copy the code. Here we add a new private member variable valueRate to Goods, which indicates the value coefficient of the Goods and the Cont of the internal class. Use the value () method of ent to multiply the value. We found that value () can access valueRate, which is the second advantage of the internal class. An internal class object can access the content of the external class object that creates it, and even include private variables! This is a very useful feature that provides us with more ideas and shortcuts during design. To implement this function, internal class objects must have references to external class objects. When creating an internal class object, the java compiler implicitly transfers the objects of other external classes and stores them all the time. In this way, internal class objects can always access their external class objects. This is also why external class objects must be created to create internal class objects out of the scope of the external class. Someone may ask, what if a member variable of an external class has the same name as a member variable of an internal class, that is, the member variable of the external class is blocked? Nothing. There is a reference to the external class in the following format in java: outerClass. this has it, so we are not afraid of such blocking. Static internal classes are the same as normal classes. Internal classes can also be static. However, compared with non-static internal classes, the difference is that static internal classes do not reference external classes. This is actually very similar to the nested class in c ++. The biggest difference between a java internal class and a c ++ nested class is whether it points to external class references. Of course, there are some differences from the design details and some other perspectives. 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 everything. This is also the second difference between the two. Local internal class: Yes. java internal classes can be defined in a method or even a code block. Copy the public class TestInnerClass {public static void main (String args []) {Goods good = new Goods (); Destination destination = good. dest ("beijing"); System. out. println (destination. readLabel () ;}} interface Destination {String readLabel ();} class Goods {public Destination dest (String s) {class GDestination implements Destination {private String label; public GDestination (String whereTo) {label = wher ETo;} public String readLabel () {return label;} return new GDestination (s) ;}} copy the code above as an example. In the dest () method, we define an internal class, And finally this internal class is returned by this method. If we only need to create an object and create it to the external when creating an object, we can do this. Of course, the internal class defined in the method can diversify the design, and its purpose is not only in this regard. The following is a more strange example: copy the code public class TestInnerClass {private void into (boolean B) {if (B) {class GDestination {private String label; public GDestination (String whereTo) {label = whereTo;} public String readLabel () {return label;} GDestination destination = new GDestination ("beijing"); System. out. println (destination. readLabel () ;}} public void dest (boolean B) {into (B);} public static void main (Strin G args []) {TestInnerClass inner = new TestInnerClass (); inner. dest (true) ;}} copy the code. You cannot create an internal Class Object outside of the if () statement. This should be beyond its scope. However, during compilation, the internal class GDestination is compiled at the same time as other classes, but it has its own scope. If it exceeds this range, it is invalid. It is no different from other internal classes. The anonymous internal class java's anonymous internal class looks odd, but like an anonymous array, when you only need to create a Class Object and cannot use its name, using Internal classes seems to make the code more concise and clear. His syntax rules are as follows: new interfaceName (){...................}; or: new superClassName () {................................}; next we will continue with the example above: copy the code public class TestInnerClass {public Contents cont () {return new Contents () {private int I = 11; public int value () {return I ;};} public static void main (String args []) {TestInnerClass test = new TestInnerClass (); Contents content = test. cont (); System. out. println (cont Ent. value () ;}} interface Contents {public int value () ;}copy the cont () in the code to directly return a class object that implements the Contents interface using an anonymous internal class, it looks really concise. In the anonymous adapter of java's event processing mechanism, anonymous internal classes are widely used. For example, when the window is closed, append the following code: frame. addWindowListener (new WindowAdapter () {public void windowClosing (invalid wevent e) {System. exit (0) ;}}); note that the anonymous internal class has no name, so he has no Constructor (but if this anonymous internal class inherits a parent class that only contains the constructor with parameters, these parameters must be included when creating the class, and use the super keyword to call the corresponding content during implementation ). If you want to initialize its member variables, you can use the following methods: if it is in an anonymous internal class of a method, you can use this method to pass in the desired parameter, but remember, these parameters must be declared as final. The anonymous internal class is transformed into a local internal class with a name, so that it can have constructor. Use the initialization code block in this anonymous internal class. Why Internal classes? What are the advantages of java internal classes? Why Internal classes? First, let's take a simple example. If you want to implement an interface, but a method in this interface has the same name and parameter as a method in the class you have conceived, what should you do? At this time, you can create an internal class to implement this interface. Because the internal class can access all the content of the external class, you can directly implement this interface. But you may have to question it. Can you just change the method? Indeed, the reason for designing the internal class is unconvincing. The real reason is that the combination of internal classes and interfaces in java can solve a problem that is often complained by C ++ programmers that java has not inherited much. In fact, the multi-inheritance design of c ++ is complex, and java can achieve multi-inheritance through internal classes + interfaces.

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.