3 minutes to take you to understand: member inner class in Java object-oriented

640?wx_fmt=jpeg&wxfrom=5&wx_lazy=1


In the last article, we talked about an important feature of Java - "encapsulation", and the use of inner classes can provide better encapsulation.


Memories:

The main role of the inner class:

  1. Inner classes provide better encapsulation, can hide the inner inside the outer, and do not allow other classes in the same package to access the class

  2. The methods of the inner class can directly access all 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.


The inner class can be simply divided into 4 types, namely:

  • member inner class

  • static inner class

  • method inner class

  • anonymous inner class


  • member inner class

Member inner class is the most common inner class, also known as ordinary inner class, because member inner class is defined inside the outer class (MD nonsense), which is equivalent to a member variable of the outer class, so it is called member inner class.

for example:

640?wx_fmt=png&wxfrom=5&wx_lazy=1

Through this simple example, we know how to use the member inner class and some characteristics:

  1. Inner classes can use any access controller (public, protected, private, etc.)

  2. The methods in the inner class can directly access the data of the outer class. As shown in the figure, the show( ) method in the inner class SiChuan can directly access the private property popu in the outer class China.


    640?wx_fmt=png

  3. To create an inner class object, you must use the outer class object, and you cannot directly new an inner class object.


    640?wx_fmt=png


Note: When the outer class and the inner class have member variables or methods with the same name, the inner class accesses the member variables or methods of the inner class by default. If you want to access the member variables of the outer class with the same name, you can use the this keyword. Such as:

640?wx_fmt=png

640?wx_fmt=png

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324519445&siteId=291194637