首页 技术 正文
技术 2022年11月17日
0 收藏 607 点赞 3,554 浏览 1644 个字

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

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

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

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

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

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

 class Test001Sub {
public Test001Sub(String s) {
System.out.println(s);
} void f() {
System.out.println("Test001->f()");
} // 一个内部类
public class Test001Inner {
public Test001Sub callOuter() {
return Test001Sub.this;
}
}
} public class Test001 {
public static void main(String[] args) {
Test001Sub t1 = new Test001Sub("new Test001"); // new Test001
Test001Sub.Test001Inner t1Inner = t1.new Test001Inner();
Test001Sub t2 = t1Inner.callOuter();
t2.f(); // Test001->f()
System.out.println(t1.equals(t2)); // true
}
}

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

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

 interface Contents {
int value();
} interface Destination {
String readLabel();
} class Test002Sub {
protected class Test002Inner1 implements Destination {
private String s; private Test002Inner1(String s) {
this.s = s;
} @Override
public String readLabel() {
return s;
}
} private class Test002Inner2 implements Contents {
private int i = 11; @Override
public int value() {
return i;
}
} public Test002Inner1 instanceInner1(String s) {
return new Test002Inner1(s);
} public Test002Inner2 instanceInner2() {
return new Test002Inner2();
}
} public class Test002 {
public static void main(String[] args) {
Test002Sub test002 = new Test002Sub();
Destination test002Impl1 = test002.instanceInner1("Test002Inner1");
Contents test002Impl2 = test002.instanceInner2();
System.out.println(test002Impl1.readLabel()); // Test002Inner1
System.out.println(test002Impl2.value()); // 11
// 外部通过引用不能访问protected及private对象
// Test002Sub.Test002Inner1 a = test002.new Test002Inner1("a");
// Test002Sub.Test002Inner2 b = test002.new Test002Inner2();
}
}
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,085
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,560
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,409
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,182
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,819
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,902