Inner class in JAVA-member inner class

Q: What is an inner class?

Answer: Inner Class is a class defined in another class. Correspondingly, the class that contains the inner class is called the outer class.

Question: Why should one class be defined in another class? What a refreshing and independent class! !

Answer: The main functions of internal classes are as follows:

1. The inner class provides better encapsulation. The inner class can be hidden in the outer class, and other classes in the same package are not allowed to access the class

2. The methods of the inner class can directly access all the data of the outer class, including private data

3. The functions implemented by the inner class can also be realized by using the outer class, but sometimes it is more convenient to use the inner class

Q: How many kinds of internal classes are there?

Answer: Inner classes can be divided into the following types:
member inner classes
static inner classes
method inner classes
anonymous inner classes

 

1. Member inner class

operation result:

From the above code, we can see how to use the inner class of the member :

1. The Inner class is defined inside the Outer class, which is equivalent to the position of a member variable of the Outer class. The Inner class can use any access control symbols, 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 controller, such as direct access to the 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, instead of going directly to new an inner class object, that is: inner class object name = outer class object. new inner class ();

 


Friendly Tips :
1. The members and methods of the inner class cannot be used directly by the external class.
2. If the outer class and the inner class have the same member variables or methods, the inner class will access its own member variables or methods by default. For member variables, you can use this keyword.

Guess you like

Origin blog.csdn.net/liushulin183/article/details/46672767