[20-05-15][Thinking in Java 18]Java Inner Class 2 - .this & .new

 1 package test_13_3;
 2 
 3 public class Outer {
 4     
 5     public Outer() {
 6         
 7         System.out.println("this is Outer");
 8     }
 9 
10     class Inner {
11         
12         public Inner() {
13             
14             System.out.println("this is Inner");
15         }
16         
17         public Outer getOut() {
18             // 如果需要生成对外部类对象的引用,可以使用外部类的名字后面加.this
19             // 这样产生的引用自动地具有正确的类型
20             return Outer.this;
21         }
22     }
23     
24     public void print() {
25         
26         System.out.println("this is Outer.print()");
27     }
28     
29 }
 1 package test_13_3;
 2 
 3 public class Test {
 4 
 5     public static void main(String[] args) {
 6 
 7         Outer outer = new Outer();
 8         // 想直接创建内部类的对象,不能引用外部类的名字,而必须使用外部类的对象来创建该内部类的对象
 9         // 同时也解决了内部类名字作用域的问题
10         Outer.Inner inner = outer.new Inner();
11         
12         inner.getOut().print();
13     }
14 }

结果如下:

this is Outer
this is Inner
this is Outer.print()

猜你喜欢

转载自www.cnblogs.com/mirai3usi9/p/12897821.html