嵌套类
来源:互联网 发布:学java好还是学ios好 编辑:程序博客网 时间:2024/04/29 23:19
通常称为嵌套类(nested class)4。想要理解static应用于内部类时的含义,你就必须记
住,普通的内部类对象隐含地保存了一个引用,指向创建它的外围类对象。然而,当内部
类是static的时,就不是这样了。嵌套类意味着:
1. 要创建嵌套类的对象,并不需要其外围类的对象。
2.不能从嵌套类的对象中访问非静态的外围类对象。
嵌套类与普通的内部类还有一个区别。普通内部类的属性与方法,只能放在类的外部层次
上,所以普通的内部类不能有 static 数据和 static 属性,也不能包含嵌套类。但是嵌套类
可以包含所有这些东西:
//: c08:Parcel10.java
// Nested classes (static inner classes).
public class Parcel10 {
private staticclass ParcelContents implements Contents {
private int i = 11;
public int value() {return i; }
}
protected staticclass ParcelDestination
implements Destination {
private String label;
private ParcelDestination(String whereTo) {
label = whereTo;
}
public String readLabel() { return label; }
// Nested classes can contain other static elements:
public static void f() {}
static int x = 10;
static class AnotherLevel {
public static void f() {}
static int x = 10;
}
}
public static Destination dest(String s) {
return new ParcelDestination(s);
}
public static Contents cont() {
return new ParcelContents();
}
public static void main(String[] args) {
Contents c = cont();
Destination d = dest("Tanzania");
}
} ///:~
在 main()中,没有任何 Parcel10 对象是必需的;取而代之的是,你要使用选取一个 static
成员的普通语法,来调用返回 Contents 和 Destination 引用的方法。
你将会看到,在一个普通的(非静态)内部类中,通过一个特殊的 this 引用,可以链接到
其外围类对象。嵌套类就没有这个特殊的 this 引用,这使得它类似于一个 static 方法。
正常情况下,你不能在接口内部放置任何代码,但嵌套类可以作为接口的一部分,因为它
是 static 的。只是将嵌套类置于接口的命名空间内,这并不违反接口的规则:
//: c08:IInterface.java
// Nested classes inside interfaces.
public interface IInterface {
static class Inner {
int i, j, k;
public Inner() {}
void f() {}
}
} ///:~
我曾在本书中建议过,在每个类中都写一个 main()方法,以用来测试这个类。这样做有一
个缺点,你必须带着那些编译了的额外代码。如果这对你是个麻烦,你可以使用嵌套类来
放置测试代码。
//: c08:TestBed.java
// Putting test code in a nested class.
public class TestBed {
public TestBed() {}
public void f() { System.out.println("f()"); }
public static class Tester {
public static void main(String[] args) {
TestBed t = new TestBed();
t.f();
}
}
} ///:~
这生成了一个独立的类 TestBed$Tester(要运行这个程序,执行 java TestBed$Tester
即可)。你可以使用这个类来做测试,但是你不必在发布的产品中包含它,只需简单地在
将产品打包前删除 TestBed$Tester.class。
- 嵌套类
- 嵌套类
- 嵌套类
- 嵌套类
- 嵌套类
- 嵌套类
- 嵌套类
- 嵌套类
- 嵌套类
- 嵌套类
- 嵌套类
- 嵌套类
- 嵌套类
- 嵌套类
- 嵌套类
- 嵌套类
- 嵌套类
- 嵌套类
- Java中的Enum的使用与分析
- SQL连接知识理解
- Linux2.6--进程抢占和上下文切换
- 程序员的困境
- linux安装IE
- 嵌套类
- matlab导出数据(fprintf,dlmwrite,xlswrite)
- 引用外围类的对象
- mysql 日志
- js window.location构建一个面包屑路径
- 内部类可以被重载吗?
- 《C语言深度剖析》学习笔记----C语言关键字
- SQL Server 2008R2编写脚本时智能提示功能丢失的处理方法
- 深入理解计算机系统(第二版) 家庭作业 第七章