Deep analysis based on the functions of Java inner class _java

Source: Internet
Author: User
Tags anonymous inheritance
The mention of Java internal class (Inner Class) may be unfamiliar to many people, in fact, similar concepts in C + +, that is, nested class (Nested Class), about the difference between the two and the connection, in the following will be compared. The inner class looks at the surface, is to define a class in the class (see below, the inner class can be defined in many places), but it is not so simple, at first glance the inner class seems superfluous, and its usefulness may not be so significant to the beginner, but with the deep understanding of it, You will find that the Java designer is really well-intentioned in the inner class. Learning to use internal classes is part of Mastering Java Advanced Programming, which allows you to design your program structure more gracefully. the following are described in the following ways:
First time to meet
Copy Code code as follows:

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, class content and gdestination are defined within the class goods, and each has protected and private modifiers to control the access level. Content represents the contents of goods, and gdestination represents the destination of goods. They implement two interface content and destination respectively. In the main method that follows, you use Contents C and destination D directly, and you don't even see the names of these two inner classes! The first benefit of the inner class, then, is to hide the actions that you don't want others to know, or encapsulation.
At the same time, we have discovered that the first way to get an inner class object outside the scope of the outside class is to create and return it using the methods of its external classes. This is done by the Cont () and Dest () methods in the previous example. So 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 When you create a Non-static inner class object, you must first create the corresponding external class object. As for the reason, it leads us to the next topic Non-static Inner Class object has a reference to its outer class object. to make a slight amendment to the example just now:
Copy Code code as follows:

public class Goods {
private int valuerate = 2;
Private class Content implements Contents {
private int i = one * 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 ();
}
}

Here we add a private member variable valuerate to the goods class, meaning that the value factor of the goods is multiplied by the value of the method value () of the internal class content. We find that value () can access valuerate, which is also the second benefit of the inner class an internal class object can access the contents of the external class object that created it, even the private variable! This is a very useful feature that provides us with more ideas and shortcuts in design. To implement this functionality, an inner class object must have a reference to an external class object. When the Java compiler creates an internal class object, it implicitly passes the reference to its outer class object and keeps it in place. This allows the inner class object to always be able to access its external class object, and this is why outside classes are scoped to create an internal class object that must first create its outer class object.
One might ask if a member variable in an inner class has the same name as a member variable of an outer class, or a member variable with the same name as the outer class is blocked, what should I do? It's okay, Java. The reference to the external class is expressed in the following format:
Outerclass.this
With it, we are not afraid of this shielding situation.

static Inner class

As with ordinary classes, inner classes can also have static. However, as opposed to non-static inner classes, the difference is that static inner classes do not have references to external ones. This is actually very much like the nested classes in C + +, and the biggest difference between Java internal classes and C + + nested classes is whether there is a reference to the outside, and of course there are differences from the design point of view and some details.
In addition, in any non-static inner class, there can be no static data, static methods, or another static inner class (The inner class may be nested more than one layer). But the static inner class can have it all. This is the second difference between the two.

local Inner class

Yes, the Java inner class can also be local, and it can be defined within a method or even a block of code.
Copy Code code as follows:

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 of this. In method Dest we define an inner class, and finally this method returns the object of the inner class. If we use an inner class just to create an object of it and create it externally, we can do so. Of course, the internal classes defined in the method can diversify the design, not just at this point.
Here's a more bizarre example:
Copy Code code as follows:

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 object of this inner class outside of if, because it is beyond its scope. At compile time, however, the inner class Trackingslip is compiled at the same time as the other classes, except that it is invalidated by its own scope and beyond this scope, except that it is not different from other internal classes.

Anonymous Inner class

The syntax rules for the anonymous inner class of Java look odd, but like an anonymous array, when you just need to create a class object and can't use its name, using an inner class makes the code look neat and clear. Its grammatical rules are this:
New InterfaceName () {...}; or new Superclassname () {...};
let's go ahead with the example:
Copy Code code as follows:

public class Goods3 {
Public Contents cont () {
return new Contents () {
private int i = 11;
public int value () {
return i;
}
};
}
}

Here the Method cont () Returns an object of the class that implements the interface contents directly using the anonymous inner class, which looks really neat.
Anonymous internal classes are used in a large number of anonymous adapters in Java event handling. For example, when you want to close a window, add a code like this:
Copy Code code as follows:

Frame.addwindowlistener (New Windowadapter () {
public void windowclosing (WindowEvent e) {
System.exit (0);
}
});

One thing to be aware of is that an anonymous inner class does not have a constructor because it has no name (but if the anonymous inner class inherits a parent class that contains only the parameter constructor, you must take these parameters when you create it, and call the corresponding content with the Super keyword during implementation). If you want to initialize its member variables, there are several ways:
If you are in the anonymous inner class of a method, you can use this method to pass in the parameters you want, but remember that these parameters must be declared final.

The anonymous inner class is changed to a local inner class with a name so that it can have a constructor.
Use the initialization code block in this anonymous inner class.
Why do I need an inner class?

What are the benefits of a Java internal class? Why do I need an inner class?
Let's start with a simple example, if you want to implement an interface, but one of the methods in this interface and the name of a method in the class you are thinking about, what should you do? At this point, you can build an inner class to implement this interface. Because all of the content of the inner class external classes is accessible, this completes all the functionality that you can implement directly on this interface.

But you may have to question it, would you please change the method?
Indeed, the reason for designing the inner class is not convincing.
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 not much inheritance. In fact, the multiple inheritance of C + + design is very complex, and Java through the internal class plus interface, can be very good to achieve the effect of multiple inheritance.

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.