Member Inner classes in Java
The most common inner class is the member inner class, also known as the ordinary inner class. Let's look at the following code:
The result of the operation is:
As we can see from the code above, the use of the members ' inner classes is as follows:
1. The Inner class is defined inside the Outer class and is equivalent to the position of a member variable of the Outer class, and the Inner class can use any access control, such as public, protected, private, etc.
2. The test () method defined in the Inner class can directly access the data in the Outer class without being affected by the access control, such as direct access to private property A in the Outer class
3, after defining the member inner class, you must use the Outer class object to create the inner class object, but not directly to the new inner class object, namely: The Inner class object name = Outer class object. New inner class ();
4, after compiling the above program, you will find that two. class files have been generated
Where the second is the. class file for the outer class, the first is the. class file for the inner class, that is, the. class file for the member's inner class is always the case: the outer class name $ internal class name. class
In addition, friendly hints OH:
1. External classes cannot use the members and methods of the inner class directly.
You can first create an object of an inner class and then access its member variables and methods through the objects of the inner class.
2. If the external class and the inner class have the same member variable or method, the inner class accesses its own member variable or method by default, and if you want to access the member variable of the external class, you can use the This keyword. Such as:
Operation Result:
Introduction to Java within class