首页 > 编程语言 > 详细

Java内部类(2):普通的成员内部类

时间:2018-01-19 16:24:35      阅读:178      评论:0      收藏:0      [点我收藏+]

在成员内部类中要注意两点

第一:成员内部类中不能存在任何static的变量和方法;

第二:成员内部类是依附于外围类的,所以只有先创建了外围类才能够创建内部类。

 

接下来是两个例子(关键字:.this .new 内部类隐藏)

[.this] 用于内部类生成[对当前创建该内部类的外部类对象]的引用

[.new] 用于必须使用外部类的对象来创建内部类对象的场合

 1 class Test001Sub {
 2     public Test001Sub(String s) {
 3         System.out.println(s);
 4     }
 5 
 6     void f() {
 7         System.out.println("Test001->f()");
 8     }
 9 
10     // 一个内部类
11     public class Test001Inner {
12         public Test001Sub callOuter() {
13             return Test001Sub.this;
14         }
15     }
16 }
17 
18 public class Test001 {
19     public static void main(String[] args) {
20         Test001Sub t1 = new Test001Sub("new Test001"); // new Test001
21         Test001Sub.Test001Inner t1Inner = t1.new Test001Inner();
22         Test001Sub t2 = t1Inner.callOuter();
23         t2.f(); // Test001->f()
24         System.out.println(t1.equals(t2)); // true
25     }
26 }

 

protected及private的访问规则依然适用于内部类,外部通过引用不能访问protected及private对象(内部类隐藏)。

可以在外部类内部创建getInstance()方法获得内部类对象。一般推荐这种方法来创建内部类对象。

 1 interface Contents {
 2     int value();
 3 }
 4 
 5 interface Destination {
 6     String readLabel();
 7 }
 8 
 9 class Test002Sub {
10     protected class Test002Inner1 implements Destination {
11         private String s;
12 
13         private Test002Inner1(String s) {
14             this.s = s;
15         }
16 
17         @Override
18         public String readLabel() {
19             return s;
20         }
21     }
22 
23     private class Test002Inner2 implements Contents {
24         private int i = 11;
25 
26         @Override
27         public int value() {
28             return i;
29         }
30     }
31 
32     public Test002Inner1 instanceInner1(String s) {
33         return new Test002Inner1(s);
34     }
35 
36     public Test002Inner2 instanceInner2() {
37         return new Test002Inner2();
38     }
39 }
40 
41 public class Test002 {
42     public static void main(String[] args) {
43         Test002Sub test002 = new Test002Sub();
44         Destination test002Impl1 = test002.instanceInner1("Test002Inner1");
45         Contents test002Impl2 = test002.instanceInner2();
46         System.out.println(test002Impl1.readLabel()); // Test002Inner1
47         System.out.println(test002Impl2.value()); // 11
48         // 外部通过引用不能访问protected及private对象
49         // Test002Sub.Test002Inner1 a = test002.new Test002Inner1("a");
50         // Test002Sub.Test002Inner2 b = test002.new Test002Inner2();
51     }
52 }

 

Java内部类(2):普通的成员内部类

原文:https://www.cnblogs.com/storml/p/8317438.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!