We know that Java provides a language feature: an inner class. At first touching the inner class, it feels like this mechanism is really magical, but then it seems that this mechanism is somewhat superfluous. Because we can completely use the external class to implement the same functionality as the inner class, such as the Factory pattern (http://blog.csdn.net/hmzdbql/article/details/7691055) in my previous article. So what is the benefit of the inner class?
We envision a situation where if there is a Class A, a class B they implement different functions (note that at this time a, Class B is an entity class rather than an abstract class or interface). Now we need to write a class C, which needs to use all of the functions in Class A Class B, which means that we can use Class A and the methods in class B directly through Class C. Think about how it should be done? You may think of inheritance, and indeed inheritance is a good way. But soon you will find tragedy: Java does not support multiple inheritance ... Class C cannot use all methods in Class A and Class B in an inherited way. Seems to be out of the ... In fact, this time the internal class came in handy. Look at the following code:
classa{ Public voidf () {//Method Content }}classb{ Public voidg () {//Method Content }}classCextendsa{B Getb () {return NewB () {//The method of Class B can be extended here }; }} Public classtest{ Public Static voidMain (string[] args) {c C=NewC (); C.F ();//called the F () method of Class AC.getb (). g ();//the G () method of Class B was called }}
In this example we see that Class C implements a fully integrated approach to Class A and B. We only need to use Class C to use all the methods in the A-B class. In other words, we use inner classes to implement multiple inheritance ....
We can also get some additional benefits from using internal classes: we find that we can extend the Class B approach in our inner classes, which is undoubtedly a great benefit.
Of course, the above approach can be implemented in other ways instead of using an inner class. For example, we add Method Geta () to Class C, and Getb () can get a A/b object separately. You can also achieve the same effect. But if we encounter a problem that must be solved with multiple inheritance, the inner class is undoubtedly the preferred and required choice. From another aspect, we know that C + + supports multiple inheritance, and Java does not support it. Many times will cause inconvenience, with the internal class mechanism support can also achieve multiple inheritance, Java is another feature of it.
Why use internal classes