[Java Study Notes] internal class

Source: Internet
Author: User
Tags class manager

Author: gnuhpc
Source: http://www.cnblogs.com/gnuhpc/

1. Definition:

As the name implies, a class is defined in a class, which can be static or non-static. Internal classes are actually a compiler phenomenon. The compiler converts an internal class to a common class file with some strange names. The virtual machine does not distinguish files in the classes of the general class from the internal class.

2. The first benefit of using internal classes-encapsulation and multi-Inheritance

We analyze the "third relationship:

The inheritance structure has two relationships: "is a" and "has. Let's take an example of is-a of employee/manager:

Class employee {
Private string name;
Private date datehire;
.....
.....
Public float getsalary (){
}
...
}

Class manager extends employee {
Private employee [] subordinates;
....
Public Employee [] getsubordinates (){
Return subordinates;
}
} Another link is has-a, class company {
Private employee [] allemployees;
Private manager [] allmanagers;
....
Public Manager [] getallmanagers (){
Return allmanagers ();
}
Public void printorganizationtree (){
}
}
However, there is still a third relationship, which is not obvious but often used, called a "flat relationship ". Let's take an example of a car: an automobile (like automobile) can contain many components, such as an engine, a transmission system, and an exhaust system. Of course, there may also be an auto AC component ). This auto AC may be obtained from a general class airconditioner and is suitable for automobiles after transformation. However, it cannot exist independently, and the vehicle must have interaction and control with it. Note: here, the automobile class cannot implement an interface called autoac. Because a car is not an air conditioner, it should not have the attributes that the air conditioner should have. The attributes of on-board air conditioners should be placed in the automobile class. Here we use internal classes to describe and solve the problem.

/** The General airconditioner class */
Class airconditioner {
....
Public float gettemperaturemin (){
}
Public float gettemperaturemax (){
}
}

/** The automobile class which has an inner class which is an AC */
Class automobile {
Private engine;
Private gearbox;
Private autoairconditioner autoac;
.....
Private class autoairconditioner extends airconditioner {
...
Public float getbeltperimeter (){
Float adjusted volume = engine. getvolume () * 1.1;
......
}
}

Public airconditioner getairconditioner (){
}
}

The objects of the autoairconditioner class are included in the automobile class, which is a bit like an contained inheritance relationship (has-a), but there is a difference: the autoairconditioner object is open to the outside world due to the interface defined in the airconditioner class. In addition, the extension of this class is only limited to the automobile class.

In addition, the autoairconditioner internal class can access all the members of the automobile class, so you do not need to define specific access methods in the automobile class. Airconditioner in the automobile class provides some behaviors, but does not use inheritance or expose the automobile class through any public method. This makes the interface look more neat and the inheritance relationship is simpler.

Another example is to assume that different types of bolts need to be used in a vehicle design project. There may be many types of bolts, so where to use the bolts we need to try one by one at each place, then we need an iterator for the traversal on the bolts, iterator. In this case, the internal class is especially suitable for this requirement. We define an internal class iterator in the automobile class and return a reference through a public method boliterator. Even better, we can create an internal Anonymous class, because the class name is used only once, so we can simply make it anonymous and look simple. It is a typical internal application to provide a public interface for a class.

Import java. util. iterator;
Class automobile {
Bolt [] boltarray;
......
......

 Public iterator boltiterator (){
Return new iterator (){
Int count;
Public Boolean hasnext (){
Return (count <boltarray. Length );
}
Public object next (){
Return boltarray [count ++];
}
};
} // Method iterator

}
The next () and hasnext () methods can directly access private members of the automobile class. It is noted that the behavior of the automobile class and the behavior of the iterator are not physically related. They are just flat relationships. An internal class object can access the content of its external class object, and even include private variables! Imagine that if there is no internal class mechanism, only one class itr is implemented outside automobile. This class has an automobile instance Member automobile, so that itr can obtain the internal information of automobile for traversal, automobile must provide additional access interfaces to itr.

3. Internal category Exploration

The internal class can be a private member in the condition class, which is a trick of the compiler. For example, the class file of the internal class autoairconditioner may be automobile $ autoairconditioner. Class. In the class file, there is a private final reference, called this $0 pointing to an external class, which is generated by the compiler. Through this reference, the internal class can access the members of the External class. However, this is not enough. Some access methods in the external class should also be generated by the compiler. For example, if the internal class autoairconditioner can directly access the private variable engine in the automobile class, the class file of the automobile class will contain a method static engine access $0 (automobile ). Of course, these are all done without your perception.

If a member variable in an internal class has the same name as a member variable of an external class, that is, the member variable with the same name of the external class is blocked, Java uses the following format to express reference of the external class: outerclass. this.

Note: In any non-static internal class, there cannot be static data, static methods, or a static internal class (internal class nesting can be more than one layer ). However, static internal classes can have all of this.

4. Use the second role of the internal class-limited operation

Suppose we have a databaseservice class that maintains a database connection pool, where an execute (string query) method extracts a connection from the pool, executes the query statement, and then returns it. Now we have a program that needs to get the connection handle directly, but we don't want it to use the connection object at will. We just want to give it limited operations.

Class databaseservice {
Private connection [] pool;
.....
Public resultset execute (string sqlstmt ){
..........
}
PrivateConnection getfreeconnectionfrompool (){
......
}
Private void checkinfreeconnection (connection conn ){
.......
}
Public controlledconnection getcontrolledconnection (){
Return new controlledconnectionimpl ();
}
.....
// Inner class to encapsulate one connection object and keep it under control
Class controlledconnectionimpl implements controlledconnection {
Private connection myconnection;
Private int operationcount;
Private controlledconnection (){
// Access private method of class databaseservice
Myconnection = getfreeconnectionfrompool ();
}
Public object operateonconnection (string operation, object [] ARGs ){
Operationcount ++
If (operation. Equals ("createstatement ")){
}
Else if (operation. Equals ("preparestatement ")){
}
Else if (operation. Equals ("commit ")){
}
......
}
}
}

Internal controlledconnectionimpl only has one method that can be used by external programs,Operateonconnection (). We noticed that the constructor of this internal class is private. That is to say, only the databaseservice object instance can create this object. External programs only pass throughThe getcontrolledconnection () method can obtain this instance.

We noticed that in the databaseservice classgetFreeeConnectionFromPool()The method is private, so external programs are not available. Currently, there are two methods for internal class control permissions: the first method is to provide some interfaces to external entities, and the second method is to provide a similaroperateOnConnection()In this example, you can agree that a connection can only be operated in three steps.Operationcount variable.

6. Methods for obtaining internal class objects out of the scope of external classes,

Use the method provided by its external class to create and return. Public XXXX getxxx (){

Return new xxxx ();

}

Use the basic syntax:

Outerobject = new outerclass (constructor parameters );

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

Note: When creating a non-static internal class object, you must first create an external class object.

8. static internal class

The static internal class does not point to external references and can only access static members of the external class,Non-static members must be accessed by creating external class objects. The purpose of using static internal classes is the same as that of using internal classes. If an internal class does not depend on the instance variables of its external class or has nothing to do with the instance variables, select the static internal class of the application. Another argument is that B is a helper class of A and can be defined as a static internal class only when B is used as.

9. Anonymous internal class:

Anonymous internal classes are developed based on the concept of abstract classes and interfaces. The main purpose is to reduce the definition of a class when a class that inherits or implements an interface is used only once. The so-called anonymity means that the class does not even have a name. The anonymous internal class cannot have a constructor, and it can access all the member variables and methods in the external, including private, the interface or inheritance class cannot be implemented. Similarly, if you want to access parameters in the internal class access method defined in the method, you must add "final" to the declaration of the method parameters to ensure the call consistency when passing them to the internal class: there are many anonymous internal class objects that have much longer survival scope than a method call, such as listeners and threads. therefore, you only need to copy these references. If they are not final, you can still assign values at will, and the copy in the internal class will expire.

10. Notes:

1) the class defined in a method is also a local internal class. The local internal class is the same as the instance internal class and can access all members of all external classes. In addition, local internal classes can also access final parameters and variables in the method.

2) Internal classes can be defined as abstract classes.

 

Author: gnuhpc
Source: http://www.cnblogs.com/gnuhpc/

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.