【编程思想笔记】内部类的初始化

看编程思想有点时间了,看到了些在马士兵老师没有讲过的部分,所以打算记录一下

内部类的初始化:

.内部类的初始化和外部类的初始化略有不同,可以使用 外部类对象.new 内部类对象 创建内部类对象

 1 package com.github.hellxz.practice10_2_2;
 2 
 3 public class Outer {
 4     public String toString() {
 5         return "Outer class override toString() method";
 6     }
 7     class Inner{
 8         public String toString() {
 9             return "Inner class override toString() method";
10         }
11     }
12     public static void main(String args[]) {
13         //this is wrong way to create inner class instance
14         //! Inner inner = new Outer.Inner();
15         Outer outer = new Outer(); //create outer instance first ,cuz an inner instance must create on a outer instance
16         Inner inner = outer.new Inner(); //create inner instance. 
17         //the declare type also can be Outer.Inner
18         Outer.Inner inner2 = outer.new Inner();
19     }
20 }

内部类对象返回外部类对象的引用:

.使用 .this  在上边代码的基础上修改代码

 1 package com.github.hellxz.test;
 2 
 3 public class Outer {
 4     public String toString() {
 5         return "Outer class override toString() method";
 6     }
 7     class Inner{
 8         //a method to return outer class reference
 9         Outer outer() {
10             return Outer.this;
11         }
12         public String toString() {
13             return "Inner class override toString() method";
14         }
15     }
16     public static void main(String args[]) {
17         Outer outer = new Outer(); 
18         System.out.println(outer); //show which reference
19         Inner inner = outer.new Inner(); 
20         System.out.println(inner); 
21         // use inner class method to return outer class reference
22         //! Inner inner2 = inner.outer(); //it wrong
23         Outer outer2 = inner.outer();
24         System.out.println(outer2);
25     }
26 }
27 
28 //output:
29 //Outer class override toString() method
30 //Inner class override toString() method
31 //Outer class override toString() method

 

问我为啥注释都英文,因为我这linuxmint的root用户的fcitx好像没装好。在普通用户下正常,一使用root用户就不行,百度好久也没解决,有知道解决方法的老哥评论下告知呗,小弟感激不尽!

posted @ 2017-12-10 20:32  东北小狐狸  阅读(1235)  评论(0编辑  收藏  举报