Java language-Analysis of Internal classes in Java

Source: Internet
Author: User
Java language-Analysis of Internal classes in Java-general Linux technology-Linux programming and kernel information. The following is a detailed description. Many people may not be familiar with the Inner Class mentioned in Java. In fact, similar concepts also exist in C ++, that is, 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 heart for 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 interface Contents {
Int value ();
}

Public interface Destination {
String readLabel ();
}

Public class Goods {
Private class Content implements 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 Destination dest (String s ){
Return new GDestination (s );
}
Public Contents cont (){
Return new Content ();
}
}

Class TestGoods {
Public static void main (String [] args ){
Goods p = new Goods ();
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 = new outerClass (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 ?? A non-static internal class object has a reference pointing to its external Class Object. Modify the example just now:

Public class Goods {

Private 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;
Private GDestination (String whereTo ){
Label = whereTo;
}
Public String readLabel (){
Return label;
}
}

Public Destination dest (String s ){
Return new GDestination (s );
}
Public Contents cont (){
Return new Content ();
}
}

The modified part is displayed in blue. Here we add a private member variable valueRate to the Goods class, which indicates the value coefficient of the Goods. The value () of the Content Method of the internal class is multiplied when it calculates the value. 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 object, 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 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 why external class objects must be created before they are created outside the scope of the external class.

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 class Goods1 {
Public Destination dest (String s ){
Class GDestination implements Destination {
Private String label;
Private GDestination (String whereTo ){
Label = whereTo;
}
Public String readLabel () {return label ;}
}
Return new GDestination (s );
}

Public static void main (String [] args ){
Goods1 g = new Goods1 ();
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 class Goods2 {
Private void internalTracking (boolean B ){
If (B ){
Class TrackingSlip {
Private String id;
TrackingSlip (String s ){
Id = s;
}
String getSlip () {return id ;}
}
TrackingSlip ts = new TrackingSlip ("slip ");
String s = ts. getSlip ();
}
}

Public void track () {internalTracking (true );}

Public static void main (String [] args ){
Goods2 g = new Goods2 ();
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:

New interfacename () {...}; or new superclassname (){......};

Next we will continue with the example above:

Public class Goods3 {
Public Contents cont (){
Return new Contents (){
Private int I = 11;
Public int value (){
Return I;
}
};
}
}

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 (new WindowAdapter (){
Public void windowClosing (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:

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.

The anonymous internal class is transformed into a local internal class with a name, so that it can have constructors.

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 combination of internal classes and interfaces in java can solve a problem that is often complained by C ++ programmers in java ?? There is no multi-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.
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.