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:
Task
Little friends, let's do a practice to solidify the use of members ' internal classes!
The member inner class Inner is defined in the editor, and the property values of the outer and inner classes are output in the show method of the inner class.
Program Run Result:
Please complete the code in section 15, 16, and line
//External class HelloWorld Public classhelloworld{//Private property of the external class name PrivateString name = "Imooc"; //member properties for external classes intAge = 20; //member Inner class inner Public classInner {String name= "Adoration Class"; //methods in the inner class Public voidShow () {System.out.println ("Name in the External class:" + HelloWorld. This. Name); System.out.println ("Name in the Inner class:" +name); System.out.println ("Age in the Outer class:" +Age ); } } //Test member Inner class Public Static voidMain (string[] args) {//create an object of an external classHelloWorld o =NewHelloWorld (); //to create an object of an inner classInner inn = O.NewInner (); //call the Show method of an inner class objectinn.show (); }}
Member Inner classes in Java