In Java, a class can be defined inside another class or inside a method, and such a class is called an inner class. The broad range of internal classes generally includes these four types: member inner class, local inner class, anonymous inner class, and static inner class.
The member inner class is the most common inner class, defined as being inside another class, as in the following form:
| 1234567891011 |
classCircle { doubleradius = 0; public Circle(doubleradius) { this.radius = radius; } classDraw { //内部类 public voiddrawSahpe() { System.out.println("drawshape"); } }} |
This looks like the class draw is a member of the class circle, called the outer class. Member inner classes have unconditional access to all member properties and member methods of the external class, including private and static members. It is important to note, however, that when a member inner class has a member variable or method with the same name as an external class, there is a hidden phenomenon, that is, by default, members of the members inner class are accessed. If you want to access a member of the same name as an external class, you need to access it in the following form:
| 12 |
外部类.this.成员变量外部类.this.成员方法 |
Although members of the inner class can access the members of an external class unconditionally, the external class would like to access members of the member's inner class but not so much. In an external class, if you want to access members of a member's inner class, you must first create an object of a member's inner class, and then access it by reference to the object, where the member's inner class exists, that is, if you want to create an object of the member's inner class, provided that an object of an outer class must exist. The general way to create a member's inner class object is as follows
| 1234567891011121314151617181920212223242526272829 |
publicclassTest { publicstaticvoidmain(String[] args) { //第一种方式: Outter outter = newOutter(); Outter.Inner inner = outter.new Inner(); //必须通过Outter对象来创建 //第二种方式: Outter.Inner inner1 = outter.getInnerInstance(); }} classOutter { privateInner inner = null; publicOutter() { } public Inner getInnerInstance() { if(inner == null) inner = newInner(); returninner; } classInner { publicInner() { } }} |
Java Internal classes