Java internal class and anonymous internal class

Source: Internet
Author: User

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 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 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 --
Non-static internal class objects have references to their external class objects.
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 the internal class-an internal class object can access the content of the external class object that creates it, and even includes 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 evenCodeWithin the 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:
// Return function () {......}; in JS
New interfacename () {...}; or new superclassname (){......};
// Interface name or parent class name
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 Java programming In the anonymous adapter for 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 internal classes and interfaces in Java can be combined to solve the problem.ProgramThe employee complained about a problem in Java-there was 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.

This article is transferred fromWww.35java.com

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.