Internal and anonymous classes in Java

Source: Internet
Author: User
Mentioned Java internal class ( Inner class) Maybe many people are not familiar with it. In fact, similar concepts also exist in C ++, that is, nested classes ( Nested class). The differences and connections between the two are compared in the following section. On the surface, the internal class defines another 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 redundant. Its usefulness may not be so significant for beginners, but with its in-depth understanding, you will find that Java designers have a good experience in internal classes. Learning to use internal classes is part of advanced Java programming. It allows you to design your program structure more elegantly. The following describes how:
  • First meeting

 

Public InterfaceContents {
IntValue ();
}

Public InterfaceDestination {
StringReadlabel ();
}

Public ClassGoods {
Private ClassContent implements contents {
Private intI = 11;
Public intValue (){
ReturnI;
}
}

Protected ClassGdestinationImplementsDestination {
Private StringLabel;
PrivateGdestination (StringWhereto ){
Label= Whereto;
}
Public StringReadlabel (){
ReturnLabel;
}
}

PublicDestination DEST (StringS ){
ReturnNewGdestination (s );
}
Public ContentsCont (){
Return NewContent ();
}
}

ClassTestgoods {
Public Static void main(String []ARGs ){
Goods P =NewGoods ();
Contents c = P. cont ();
Destination d = P. DEST ("Beijing ");
}
}

In this example, the class content and gdestination are defined inside the class goods and have the protected and private modifiers respectively to control the access level. Content represents goods content, while gdestination represents goods destination. They implement the content and destination interfaces respectively. In the following main method, you can directly use contents C and destination d to perform operations. You don't even see the names of these two internal classes! In this way, the first benefit of the internal class is shown --Hide operations that 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 the internal class objects using its external class method. The cont () and DEST () methods in the preceding example do this. Is there any other way? Of course, the syntax format is as follows:

Outerobject =NewOuterclass (constructor parameters );

Outerclass. innerclass innerobject = outerobject. New innerclass (constructor parameters );

Note that when creating a non-static internal class object, you must first create an external class object. The reason leads to our next topic --

  • Non-static internal class objects have references to their external class objects.

Modify the example just now:

Public ClassGoods {

Private valuerate = 2;

Private classContentImplementsContents {
Private intI =11 * valuerate;
Public intValue (){
ReturnI;
}
}

Protected classGdestinationImplementsDestination {
Private stringLabel;
PrivateGdestination (StringWhereto ){
Label= Whereto;
}
Public StringReadlabel (){
ReturnLabel;
}
}

PublicDestination DEST (StringS ){
Return newGdestination (s );
}
PublicContents cont (){
Return NewContent ();
}
}

 

The modified part is highlighted in blue. t he is sorry. added a private member variable valuerate to the oods class, which indicates the value coefficient of the goods and the method value () of the content in the internal class () multiply the value when calculating it. We found that value () can access valuerate, which is also the second benefit of internal classes --An internal class object can access the content of its external Class ObjectAnd 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 pointing to external class objects. When creating an internal class object, the Java compiler implicitly transfers the reference of its external Class Object and keeps saving it. In this way, internal class objects can always access their external class objects. This is also the reason why external class objects must be created before they are created.

Someone may ask, what if a member variable in the internal class has the same name as a member variable in the external class, that is, the member variable with the same name in the external class is blocked? Nothing. Java uses the following format to express external class references:

Outerclass. This

With it, we are not afraid of such blocking.

  • Static internal class

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. This is the second difference between the two.

  • Local internal class

Yes, Java internal classes can also be local, which can be defined in a method or even a code block.

Public ClassGoods1 {
PublicDestination DEST (StringS ){
ClassGdestinationImplementsDestination {
Private stringLabel;
PrivateGdestination (StringWhereto ){
Label= Whereto;
}
Public StringReadlabel (){ReturnLabel ;}
}
Return newGdestination (s );
}

Public static Void main(String []ARGs ){
Goods1 G =NewGoods1 ();
Destination d = G. DEST ("Beijing ");
}
}

The above is an example. In the Dest method, we define an internal class. Finally, this method returns the object of this internal class. If we only need to create an object and create it to the external when using an internal class, 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:

Public ClassGoods2 {
Private VoidInternaltracking (BooleanB ){
If (B ){
ClassTrackingslip {
Private stringID;
Trackingslip (StringS ){
Id = s;
}
StringGetslip (){ReturnID ;}
}
Trackingslip Ts =NewTrackingslip ("slip ");
StringS = ts. getslip ();
}
}

Public voidTrack () {internaltracking (True);}

Public static Void main(String []ARGs ){
Goods2 G =NewGoods2 ();
G. Track ();
}
}

You cannot create an internal Class Object outside of if because it is beyond its scope. However, during compilation, the internal class trackingslip is compiled at the same time as other classes, except that it is in its own scope and is invalid if it exceeds this scope, it is no different from other internal classes.

  • Anonymous internal class

The syntax rules for anonymous internal classes in Java seem odd, but like an anonymous array, when you only need to create a Class Object and cannot use its name, using Internal classes can make the Code look concise and clear. Its syntax rules are as follows:

NewInterfacename () {...}; orNewSuperclassname (){......};

Next we will continue with the example above:

Public classGoods3 {
PublicContents cont (){
Return NewCONTENTS (){
Private intI = 11;
Public intValue (){
ReturnI;
}
};
}
}

Here, the cont () method uses an anonymous internal class to directly return an object of the class implementing the contents interface, which looks very concise.

In the anonymous adapter for Java event processing, anonymous internal classes are widely used. For example, add the following code when you want to close the window:

Frame.Addwindowlistener(NewWindowadapter (){
Public voidWindowclosing (windowevent e ){
System. Exit (0 );
}
});

One thing to note is that the anonymous internal class has no name, so it does not have a constructor (but if this anonymous internal class inherits a parent class that only contains a parameter constructor, these parameters must be included during creation and the corresponding content must be called using the super keyword during implementation ). If you want to initialize its member variables, you can use the following methods:

  1. If it is in an anonymous internal class of a method, you can use this method to pass in the desired parameters, but remember that these parameters must be declared as final.
  2. The anonymous internal class is transformed into a local internal class with a name, so that it can have constructors.
  3. 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? In this case, you can create an internal class to implement this interface. Since all the content of the internal class is accessible to external departments, this can complete all the functions that you can directly implement this interface.

But you may have to question it. Isn't it enough to change the method?

Indeed, it is unconvincing to use this as a reason to design internal classes.

The real reason is that the internal classes and interfaces in Java can be combined to solve a problem that C ++ programmers often complain about in Java-there is not much inheritance. In fact, the multi-inheritance design of c ++ is very complicated, and Java can implement multi-inheritance effectively by adding interfaces to internal classes.

The purpose of this article is to introduce the concepts and usage of internal classes. In subsequent articles, we will give more examples of the content in this article, describes how to use internal classes to build an applicaton framework.

 

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.