Within the Java class (Innerclass)----non-static inner classes, static inner classes, local inner classes, anonymous inner classes

Source: Internet
Author: User

Mention Java Underwear class (Innerclass) A lot of people are not familiar with, actually similar concept in C + + also has, that is nested class (Nested Class), about the difference between the two, there will be a comparison in the following. The inner class, on the surface, defines a class in a class (as you can see from the inside class, which can be defined in many places), but it's not as simple as it might seem, and his usefulness may not be so obvious to beginners, but with his deep understanding, You'll find that Java designers are really doing it on the underwear category. Learning to use internal classes is part of mastering the Advanced programming of Java, which allows you to design your program structure more elegantly. Here are a few of the following:

Meet for the first time:

 Public classtestinnerclass{ Public Static voidMain (String args[]) {Goods good=NewGoods (); Contents content=good.dest ();                System.out.println (Content.value ()); Destination Destination= Good.cont ("Beijing");    System.out.println (Destination.readlabel ()); }}Interfacecontents{intvalue ();}Interfacedestination{String Readlabel ();}classgoods{Private classContentImplementscontents{Private inti = 11;  Public intvalue () {returni; }    }    protected classGdestinationImplementsdestination{PrivateString label; Privategdestination (String whereto) {label=Whereto; }         PublicString Readlabel () {returnlabel; }    }     PublicContent dest () {return NewContent (); }     Publicgdestination Cont (String s) {return NewGdestination (s); }}

In this example, the class content and gdestination are defined inside the goods class and have private and protected modifiers to control the level of access. Content represents the contents of goods, while gdestination represents the destination of goods. In the back of the main () method, directly with contents content and destination destination to operate, you even the two internal class names have not seen, so that the benefits of the inner class is reflected, Hide the actions you don't want others to know, that is, encapsulation.

At the same time, we also discovered that the first method of getting an inner class object outside the scope of the outer class is to create and return it using the method of its outer class. The Dest () and Cont () methods in the above example do so. So, is there any other way? Of course, its syntax is as follows:

Outerclass outerobject = new Outerclass (Constructor parameters);

Outerclass.   Innerclass innerobject = outerobject.new innerclass (Constructor parameters); Of course, this time to change the number of internal class construction rows to public, can not be private

Note When creating a non-static inner class object, be sure to create the appropriate outer class object first. As for the reason, it leads us to the next topic the non-static inner class object has a reference to its Outer class object , with a slight modification to the example just now:

 Public classtestinnerclass{ Public Static voidMain (String args[]) {Goods good=NewGoods (); Contents content=good.dest ();    System.out.println (Content.value ()); }}Interfacecontents{intvalue ();}Interfacedestination{String Readlabel ();}classgoods{private int valuerate = 2; Private classContentImplementscontents{private int i = one * valuerate;  Public intvalue () {returni; }    }    protected classGdestinationImplementsdestination{PrivateString label;  Publicgdestination (String whereto) {label=Whereto; }         PublicString Readlabel () {returnlabel; }    }     PublicContent dest () {return NewContent (); }     Publicgdestination Cont (String s) {return NewGdestination (s); }}

Here we add a new private member variable valuerate, meaning is the value coefficient of the goods, in the internal class content method value () to calculate the value of the goods him on. We find that value () can access valuerate, which is also the second benefit of the inner class, an inner class object that can access the contents of creating his external class object, even including private variables! This is a very useful feature that provides us with more ideas and shortcuts in our design. To implement this function, the inner class object must have a reference to the Outer class object.

When creating an inner class object, the Java compiler implicitly passes in the objects of other external classes and keeps them. This allows objects of the inner class to always have access to the objects of their outer classes. This is also why external class objects must be created outside the scope of the outside class to create an inner class object.

One would ask, what if a member variable of an external class has the same name as a member variable of an inner class, that is, the member variable of the outer class is masked? It's okay, Java has a reference to the outer class in the following format:

Outerclass.this

With it, we are not afraid of this shielding situation.

Static Inner class

As with normal classes, inner classes can also be made from static. However, compared to non-static inner classes, the difference is that the static inner class does not have a reference to the outer class. this is actually similar to nested classes in C + +. The biggest difference between a Java inner class and a C + + nested class is whether there is a point to the external class reference, but there are some differences from the design details and other aspects.

In addition, in any non-static inner class, there can be no static data, a static method, or another static inner class (inner classes may be nested more than one layer). However, the static inner class can have all of them. This is the second difference between two people.

Local inner class:

Yes, the Java inner class can be defined inside a method or even within a block of code.

 Public classtestinnerclass{ Public Static voidMain (String args[]) {Goods good=NewGoods (); Destination Destination= Good.dest ("Beijing");    System.out.println (Destination.readlabel ()); }}Interfacedestination{String Readlabel ();}classgoods{ PublicDestination dest (String s) {classGdestinationImplementsdestination{PrivateString label;  Publicgdestination (String whereto) {label=Whereto; }             PublicString Readlabel () {returnlabel; }        }        return NewGdestination (s); }}

The above is an example of this. In Method Dest () We define an inner class, which is finally returned by this method. If we were to create an object and create an object, we could do it. Of course, the internal classes defined in the method can diversify the design, and the use is not just at this point.

Here's a more bizarre example:

 Public classtestinnerclass{Private voidIntoBooleanb) {        if(b) {classgdestination {PrivateString label;  Publicgdestination (String whereto) {label=Whereto; }                 PublicString Readlabel () {returnlabel; }} gdestination Destination=NewGdestination ("Beijing");        System.out.println (Destination.readlabel ()); }    }     Public voidDestBooleanb)    {into (b); }     Public Static voidMain (String args[]) {testinnerclass inner=NewTestinnerclass (); Inner.dest (true); }}

you can no longer create an object of this inner class outside the if () statement, which should have gone beyond his scope. however, at compile time, the inner class gdestination and other classes are compiled at the same time, but he has his own scope. Beyond this range is not valid, except that it does not differ from other internal classes.

Anonymous inner class

The anonymous inner class of Java looks a little odd, but like an anonymous array, you just need to create a class object without his name, using an inner class that looks like it will make the code more concise and clear. The rules of his grammar are this:

New InterfaceName () () {...};...};; Or: New Superclassname () {..... ...};............};

Let's go ahead and continue with the example:

 Public classtestinnerclass{ PublicContents cont () {return NewContents () {Private inti = 11;  Public intvalue () {returni;    }        }; }     Public Static voidMain (String args[]) {testinnerclass test=NewTestinnerclass (); Contents content=Test.cont ();    System.out.println (Content.value ()); }}Interfacecontents{ Public intvalue ();}

The Cont () here uses an anonymous inner class to directly return a class object that implements the interface contents, and it does look very concise.

In the anonymous adapter of the Java event handling mechanism, anonymous inner classes are used extensively. For example, when you close a window, you attach a piece of code:

Frame.addwindowlistener (new  windowadapter () {      publicvoid  Windowclosing (WindowEvent e) {         system.exit (0);      }  });   

One thing to note is that the anonymous inner class does not have a constructor because it has no name, but if the anonymous inner class inherits a parent class with only a parameter constructor, it must be created with these parameters, and the corresponding content is invoked using the Super keyword during implementation. If you want to initialize his member variables, there are several ways:

If it is an anonymous inner class in a method, you can use this method to pass in the arguments you want, but remember that these parameters must be declared final.

Change the anonymous inner class to the local inner class with the name so that he can have the constructor.

Use the initialization code block in this anonymous inner class.

Why do I need an internal class?

What are the benefits of Java internal classes? Why do I need an internal class?

Let's start with a simple example, if you want to implement an interface, but one of the methods in this interface is the same as the name of a method in the class you're envisioning, and the parameters are the same, what should you do? At this point, you can create an inner class to implement this interface. Since the inner class is accessible to all the contents of the external class, doing so can accomplish the function of directly implementing the interface.

But you may have to question, is it OK to change the method?

Indeed, it is not persuasive to justify the design of internal classes.

The real reason is that, in Java, the internal classes and interfaces together, can be resolved often by C + + programmers complain that there is a problem in Java is not much inheritance. In fact, C + + 's multi-inheritance design is very complex, and Java through the internal class + interface, can be a good implementation of multi-inheritance effect.

Within the Java class (Innerclass)----non-static inner classes, static inner classes, local inner classes, anonymous inner classes

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.