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 (nested
Class). The differences and relationships between the two are compared in the following section. On the surface, an internal class defines another class in the class (as we can see below, the internal class can be defined in many places ).
Actually, it is not that simple. It seems that the internal class is somewhat redundant at first glance. Its usefulness may not be so significant for beginners, but with its in-depth understanding, you will find that Java designers are inside
Class is indeed painstaking. Learning to use internal classes is part of advanced Java programming. It allows you to design yourProgramStructure. The following describes how:
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 ");
}
} Java multi-thread synchronized Guide
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. In the following main method, use contents C and destination
D. You didn't even see the names of these two internal classes! In this way,The first benefit of the internal class is shown-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 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 {Cause Analysis of exceptions in spring javamail emails
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 and content of the internal class.
Value () is used to multiply 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 for external class objects..
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. HoweverCompared with non-static internal classes, 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,In any non-static internal class, there cannot be static data, static methods or another static internal class(Nested internal classes can have 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, it 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;
}< br> Public String readlabel () {return label ;}
}< br> 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 the anonymous internal classDirectly returns an object that implements the contents class..
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? At this time,
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 concept and usage of internal classes. In the subsequent Article , the following describes how to use an internal class to build an applicaton framework.