《On Java 中文版 基础卷》阅读笔记 内部类 20
"定义在另一个类中的类称为内部类。"
利用内部类,你可以将逻辑上存在关联的类组织在一起,而且可以控制一个类在另一个类内的可见性。不
过内部类和组合明显不同,理解这一点非常重要。
内部类乍一看像一种简单的代码隐藏机制:将代码放在其他类的内部。
不过你会学到,内部类的作用不仅限于此。它了解包围它的类,并能与之通信,而且利用内部类编写的代码更优雅、更清晰,
尽管并非总是如此(此外,Java 8 的 lambda 表达式和方法引用也减少了对内部类的一些需求)。
刚接触内部类的时候,你会感觉它看起来很奇怪,需要一些时间才能在设计中自如地使用它们。
也许很难直接判断是否需要使用内部类,但在介绍内部类的基本语法和语义之后,11.8 节会开始阐述其优势。
本章的剩余部分会更加详尽地探讨内部类的语法。这些特性是为了语言的完备性而设计的,但是你未必会用到,至少一开始不会。
所以你目前需要的可能就是本章前面的部分,至于更详细的讨论,则可以当作参考资料。
11.1 创建内部类
和你预想的一样,创建内部类的方式就是把类定义放在一个包围它的类之中。
java
package innerclasses;
// innerclasses/Parcel1.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// Creating inner classes
public class Parcel1 {
class Contents {
private int i = 11;
public int value() { return i; }
}
class Destination {
private String label;
Destination(String whereTo) {
label = whereTo;
}
String readLabel() { return label; }
}
// Using inner classes looks just like
// using any other class, within Parcel1:
public void ship(String dest) {
Contents c = new Contents();
Destination d = new Destination(dest);
System.out.println(d.readLabel());
}
public static void main(String[] args) {
Parcel1 p = new Parcel1();
p.ship("Tasmania");
}
}
/* Output:
Tasmania
*/
在 ship() 内使用时,这些内部类看上去和普通类没什么不同。
表面上唯一的区别是,这些名字都是嵌套在 Parcel1 之中的。

更普遍的情况是,外部类有一个方法,该方法返回一个指向内部类的引用,正如在 to() 和 contents() 方法中看到的那样。
java
package innerclasses;
// innerclasses/Parcel2.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// Returning a reference to an inner class
public class Parcel2 {
class Contents {
private int i = 11;
public int value() { return i; }
}
class Destination {
private String label;
Destination(String whereTo) {
label = whereTo;
}
String readLabel() { return label; }
}
public Destination to(String s) {
return new Destination(s);
}
public Contents contents() {
return new Contents();
}
public void ship(String dest) {
Contents c = contents();
Destination d = to(dest);
System.out.println(d.readLabel());
}
public static void main(String[] args) {
Parcel2 p = new Parcel2();
p.ship("Tasmania");
Parcel2 q = new Parcel2();
// Defining references to inner classes:
Parcel2.Contents c = q.contents();
Parcel2.Destination d = q.to("Borneo");
}
}
/* Output:
Tasmania
*/

要在外部类的非静态方法之外的任何地方创建内部类的对象,必须像在 main() 中看到的那样,
将对象的类型指定为 OuterClassName.InnerClassName。

11.2 到外部类的链接
到目前为止,内部类看上去就是一种名称隐藏和代码组织机制,虽然有用,但算不上惊艳。
不过这里还有个奥妙之处。
当创建一个内部类时,这个内部类的对象中会隐含一个链接,指向用于创建该对象的外围对象。
通过该链接,无须任何特殊条件,内部类对象就可以访问外围对象的成员。
此外,内部类拥有对外围对象所有元素的访问权。
java
package innerclasses;
// innerclasses/Sequence.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// Holds a sequence of Objects
interface Selector {
boolean end();
Object current();
void next();
}
public class Sequence {
private Object[] items;
private int next = 0;
public Sequence(int size) {
items = new Object[size];
}
public void add(Object x) {
if (next < items.length)
items[next++] = x;
}
private class SequenceSelector implements Selector {
private int i = 0;
@Override
public boolean end() {
return i == items.length;
}
@Override
public Object current() {
return items[i];
}
@Override
public void next() {
if (i < items.length)
i++;
}
}
public Selector selector() {
return new SequenceSelector();
}
public static void main(String[] args) {
Sequence sequence = new Sequence(10);
for (int i = 0; i < 10; i++)
sequence.add(Integer.toString(i));
Selector selector = sequence.selector();
while (!selector.end()) {
System.out.print(selector.current() + " ");
selector.next();
}
}
}
/*
* Output:
* 0 1 2 3 4 5 6 7 8 9
*/
Sequence 是以类的形式包装起来的定长 Object 数组。
可以调用 add() 向序列末尾增加一个新的 Object(如果还有空间)。
要取得 Sequence 中的每一个对象,可以使用名为 Selector 的接口。
这是迭代器 (Iterator) 设计模式的一个例子,我们会在第 12 章进一步学习。
通过 Selector,可以检查是否到了 Sequence 的末尾 (end()),访问当前 Object (current()),以及移动到下一个 Object (next())。
因为 Selector 是一个接口,所以其他类可以用自己的方式实现该接口,而且其他方法可以以该接口为参数,来创建更通用的代码。


这里 SequenceSelector 是一个提供了 Selector 功能的 private 类。

在 main() 中,我们可以看到创建了一个 Sequence 对象,之后向其中加入了一些 String 对象。

然后通过调用 selector(),生成了一个 Selector 对象,它被用于在 Sequence 中移动和选择每个元素。

乍一看,SequenceSelector 的创建就和另一个内部类一样。
但是仔细研究一下,注意 end()、current() 和 next() 这些方法中的每一个都用到了 items,这个引用并不是 SequenceSelector 的一部分,而是外围对象的一个 private 字段。

然而,内部类可以访问外围对象的所有方法和字段,就好像拥有它们一样。这非常方便,我们在前面的示例中也看到了。
因此,内部类可以自动访问外围类的所有成员。这是怎么做到的呢?
对于负责创建内部类对象的特定外围类对象而言,内部类对象偷偷地获取了一个指向它的引用。
然后,当你要访问外围类的成员时,该引用会被用于选择相应的成员。
幸运的是,编译器会为你处理所有这些细节,但是现在你可以看到,内部类的对象只能与其外围类的对象关联创建(当内部类为非 static 时)。

内部类的对象在构造时,需要一个指向外围类对象的引用,如果编译器无法访问这个引用,它就会报错。不过这种情况大多不需要程序员干预。
11.3 使用 .this和 .new
要生成外部类对象的引用,可以使用外部类的名字,后面加上句点和 this。
这样生成的引用会自动具有正确的类型,而且是可以在编译时确定并检查的,所以没有任何运行时开销。
下面的示例演示了如何使用 .this。
java
package innerclasses;
// innerclasses/DotThis.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// Accessing the outer-class object
public class DotThis {
void f() {
System.out.println("DotThis.f()");
}
public class Inner {
public DotThis outer() {
return DotThis.this;
// A plain "this" would be Inner's "this"
// 如果直接写 "this" ,引用的会是 Inner 的 "this"
}
}
public Inner inner() {
return new Inner();
}
public static void main(String[] args) {
DotThis dt = new DotThis();
DotThis.Inner dti = dt.inner();
dti.outer().f();
}
}
/*
* Output:
* DotThis.f()
*/

有时我们想让其他某个对象来创建它的某个内部类的对象。要实现这样的功能,可以使用 .new 语法,
在 new 表达式中提供指向其他外部类对象的引用,就像下面这样:
java
package innerclasses;
// innerclasses/DotNew.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// Creating an inner class directly using .new syntax
public class DotNew {
public class Inner {
}
public static void main(String[] args) {
DotNew dn = new DotNew();
DotNew.Inner dni = dn.new Inner();
}
}

要直接创建内部类的对象,你可能会以为,要遵循和前面同样的形式,使用外部类的名字 DotNew,然而事实并非如此。
我们要使用外部类的对象来创建内部类的对象,正如我们在示例代码中所看到的那样。
这也解决了内部类的名字作用域问题,所以我们不用 dn.new DotNew.Inner()(确实也不能用)。
下面是 .new 应用于 "Parcel" 的示例:
java
package innerclasses;
// innerclasses/Parcel3.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// Using .new to create instances of inner classes
public class Parcel3 {
class Contents {
private int i = 11;
public int value() {
return i;
}
}
class Destination {
private String label;
Destination(String whereTo) {
label = whereTo;
}
String readLabel() {
return label;
}
}
public static void main(String[] args) {
Parcel3 p = new Parcel3();
// Must use instance of outer class
// to create an instance of the inner class:
Parcel3.Contents c = p.new Contents();
Parcel3.Destination d = p.new Destination("Tasmania");
}
}
除非已经有了一个外部类的对象,否则创建内部类对象是不可能的。
这是因为内部类的对象会暗中连接到用于创建它的外部类对象。
然而,如果你创建的是嵌套类(static 修饰的内部类),它就不需要指向外部类对象的引用。
11.4 内部类和向上转型
当需要向上转型为基类,特别是接口时,内部类就更有吸引力了。
(从实现某个接口的对象生成一个该接口类型的引用,其效果和向上转型为某个基类在本质上是一样的。)
这是因为,内部类(接口的实现)对外部而言可以是不可见、不可用的,这便于隐藏实现。
外部获得的只是一个指向基类或接口的引用。
我们可以为前面的示例创建接口:
java
package innerclasses;
// innerclasses/Destination.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
public interface Destination {
String readLabel();
}
java
package innerclasses;
// innerclasses/Contents.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
public interface Contents {
int value();
}
现在 Contents 和 Destination 表示可供客户程序员使用的接口。记住,接口会自动将其所有成员设置为 public 的。
当得到一个指向基类或接口的引用时,你可能甚至无法找出其确切的类型,如下例所示。
java
package innerclasses;
// innerclasses/TestParcel.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
class Parcel4 {
private class PContents implements Contents {
private int i = 11;
@Override
public int value() {
return i;
}
}
protected final class PDestination implements Destination {
private String label;
private PDestination(String whereTo) {
label = whereTo;
}
@Override
public String readLabel() {
return label;
}
}
public Destination destination(String s) {
return new PDestination(s);
}
public Contents contents() {
return new PContents();
}
}
public class TestParcel {
public static void main(String[] args) {
Parcel4 p = new Parcel4();
Contents c = p.contents();
Destination d = p.destination("Tasmania");
// Illegal -- can't access private class:
// - Parcel4.PContents pc = p.new PContents();
}
}
在 Parcel4 中,内部类 PContents 是 private 的,所以只有 Parcel4 能访问它。
普通类(非内部类)无法声明为 private 的或 protected 的,它们只能被给予 public 或包访问权限。

PDestination 是 protected 的,所以它只能被 Parcel4、相同包中的类(因为 protected 也给予了包访问权限),以及 Parcel4 的子类访问。

这意味着客户程序员对这些成员的了解是有限的,对它们的访问权也是有限的。
事实上,你甚至不能向下转型为 private 的内部类(除非有继承关系,否则也不能向下转型为 protected 的内部类),
因为无法访问其名字,就像在 TestParcel 中看到的那样。


private 内部类为类的设计者提供了一种方式,可以完全阻止任何与类型相关的编码依赖,并且可以完全隐藏实现细节。
此外,从客户程序员的角度来看,因为无法访问 public 接口之外的任何方法,所以接口的扩展对他们而言并没有什么用处。
这也为 Java 编译器提供了一个生成更高效代码的机会。
11.5 在方法和作用域中的内部类
到目前为止,你所看到的都是内部类的典型用法。
一般而言,你会编写或读到的内部类都很简单,并不难理解。
不过内部类的语法中还有很多更难理解的技术。
内部类可以在一个方法内或者任何一个作用域内创建。这么做有两个理由:
1.正如先前所演示的,你要实现某种接口,以便创建和返回一个引用;


2.你在解决一个复杂的问题,在自己的解决方案中创建了一个类来辅助,但是你不想让它公开。
在下面的示例中,我们可以修改前面的代码来使用:
1.在方法中定义的类;
2.在方法中的某个作用域内定义的类;
3.实现某个接口的匿名类;
4.这样的匿名类---它继承了拥有非默认构造器的类;
5.执行字段初始化的匿名类;
6.它通过实例初始化来执行构造(匿名内部类不可能有构造器)的匿名类。
第一个示例演示了如何在一个方法的作用域内(而不是在另一个类的作用域内)创建一个完整的类。这叫作局部内部类。
java
package innerclasses;
// innerclasses/Parcel5.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// Nesting a class within a method
public class Parcel5 {
public Destination destination(String s) {
final class PDestination implements Destination {
private String label;
private PDestination(String whereTo) {
label = whereTo;
}
@Override
public String readLabel() {
return label;
}
}
return new PDestination(s);
}
public static void main(String[] args) {
Parcel5 p = new Parcel5();
Destination d = p.destination("Tasmania");
}
}
PDestination 类是 destination() 的一部分,而不是 Parcel5 的一部分。
因此,PDestination 类在 destination() 外无法访问。

在 return 语句中的向上转型意味着 destination() 中只传出了一个指向 Destination 接口的引用。

PDestination 类的名字被放在了 destination() 中这一事实,并不意味着一旦 destination() 方法返回,得到的 PDestination 就不是一个合法的对象了。
在同一子目录下的每个类内,你都可以使用类标识符 PDestination 来命名内部类,而不会产生名字冲突。
接下来看看如何在任何作用域内嵌入一个内部类:
java
package innerclasses;
// innerclasses/Parcel6.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// Nesting a class within a scope
public class Parcel6 {
private void internalTracking(boolean b) {
if (b) {
class TrackingSlip {
private String id;
TrackingSlip(String s) {
id = s;
}
String getSlip() {
return id;
}
}
TrackingSlip ts = new TrackingSlip("slip");
String s = ts.getSlip();
}
// Can't use it here! Out of scope:
// - TrackingSlip ts = new TrackingSlip("x");
}
public void track() {
internalTracking(true);
}
public static void main(String[] args) {
Parcel6 p = new Parcel6();
p.track();
}
}
TrackingSlip 类被嵌入了一个 if 语句的作用域内。
这并不是说该类的创建是有条件的,它会和其他所有代码一起编译。
然而,它在定义它的作用域之外是不可用的。
除此之外,它看上去就像普通的类一样。
11.6 匿名内部类
下一个示例看上去有点奇怪:
java
package innerclasses;
// innerclasses/Parcel7.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// Returning an instance of an anonymous inner class
public class Parcel7 {
public Contents contents() {
return new Contents() { // Insert class definition
private int i = 11;
public int value() {
return i;
}
}; // Semicolon required
}
public static void main(String[] args) {
Parcel7 p = new Parcel7();
Contents c = p.contents();
}
}
contents() 方法将返回值的创建和用于表示该返回值的类的定义结合了起来。
此外,这个类没有名字 ------ 它是匿名的。
看起来你正在创建一个 Contents 对象,但是在到达分号之前,你说:"等等,我想插入一个类定义。"

这个奇怪的语法,意思是 "创建一个继承自 Contents 的匿名类的对象"。
通过 new 表达式返回的引用会被自动地向上转型为一个 Contents 引用。
匿名内部类语法是以下代码的简略形式:
java
// innerclasses/Parcel7b.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// Expanded version of Parcel7.java
public class Parcel7b {
class MyContents implements Contents {
private int i = 11;
@Override
public int value() {
return i;
}
}
public Contents contents() {
return new MyContents();
}
public static void main(String[] args) {
Parcel7b p = new Parcel7b();
Contents c = p.contents();
}
}
在这个匿名内部类中,Contents 是用无参构造器创建的。
如果基类需要带一个参数的构造器,应该这么做:
java
package innerclasses;
// innerclasses/Wrapping.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
public class Wrapping {
private int i;
public Wrapping(int x) {
i = x;
}
public int value() {
return i;
}
}
java
package innerclasses;
// innerclasses/Parcel8.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// Calling the base-class constructor
public class Parcel8 {
public Wrapping wrapping(int x) {
// Base constructor call:
return new Wrapping(x) { // [1]
@Override
public int value() {
return super.value() * 47;
}
}; // [2]
}
public static void main(String[] args) {
Parcel8 p = new Parcel8();
Wrapping w = p.wrapping(10);
}
}
1 将适当的参数传给基类构造器。
2 匿名内部类末尾的分号并不是用来标记类体的结束。相反,它标记表达式的结束,而该表达式恰好包含了这个匿名类。
因此,它和分号在其他地方的用法没什么不同。
尽管 Wrapping 是一个带有实现的普通类,但是它也被用作其子类的公共 "接口":

为体现变化,在这个例子中,Wrapping 的构造器需要一个参数。
也可以在定义匿名类中的字段时执行初始化:
java
package innerclasses;
// innerclasses/Parcel9.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
public class Parcel9 {
// Argument must be final or "effectively final"
// to use within the anonymous inner class:
public Destination destination(final String dest) {
return new Destination() {
private String label = dest;
@Override
public String readLabel() {
return label;
}
};
}
public static void main(String[] args) {
Parcel9 p = new Parcel9();
Destination d = p.destination("Tasmania");
}
}
如果你正在定义一个匿名类,而且一定要用到一个在该匿名类之外定义的对象,编译器要求参数引用用 final 修饰,
或者是 "实际上的最终变量"(也就是说,在初始化之后它永远不会改变,所以它可以被视为 final 的),
就像你在 destination() 的参数中看到的那样。
这里不写 final 也没有任何问题,但把它写上当作提醒通常更好。


如果只是要给一个字段赋值,上面这个示例中的方法就很好。
但是如果必须执行某个类似构造器的动作,该怎么办呢?
因为匿名类没有名字,所以不可能有命名的构造器。
借助实例初始化,我们可以在效果上为匿名内部类创建一个构造器,就像这样:
java
package innerclasses;
// innerclasses/AnonymousConstructor.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// Creating a constructor for an anonymous inner class
abstract class Base {
Base(int i) {
System.out.println("Base constructor, i = " + i);
}
public abstract void f();
}
public class AnonymousConstructor {
public static Base getBase(int i) {
return new Base(i) {
{
System.out.println(
"Inside instance initializer");
}
@Override
public void f() {
System.out.println("In anonymous f()");
}
};
}
public static void main(String[] args) {
Base base = getBase(47);
base.f();
}
}
/*
* Output:
* Base constructor, i = 47
* Inside instance initializer
* In anonymous f()
*/
这里变量 i 并不是必须为最终变量。
尽管 i 被传给了匿名类的基类构造器,但是在该匿名类内部,它并没有被直接使用到。


下面是带实例初始化的 "Parcel" 形式。注意 destination() 的参数必须是最终变量,或者是 "实际上的最终变量",因为它们在匿名类内部被用到:
java
package innerclasses;
// innerclasses/Parcel10.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// Using "instance initialization" to perform
// construction on an anonymous inner class
public class Parcel10 {
public Destination destination(final String dest, final float price) {
return new Destination() {
private int cost;
// Instance initialization for each object:
{
cost = Math.round(price);
if (cost > 100)
System.out.println("Over budget!");
}
private String label = dest;
@Override
public String readLabel() {
return label;
}
};
}
public static void main(String[] args) {
Parcel10 p = new Parcel10();
Destination d = p.destination("Tasmania", 101.395F);
}
}
/*
* Output:
* Over budget!
*/

我们在实例初始化操作内可用看到一段代码,也就是 if 语句,它们不能作为字段初始化的一部分来执行。
所以在效果上,实例初始化部分就是匿名内部类的构造器。
不过它也有局限性------我们无法重载实例初始化部分,所以只能有一个这样的构造器。
与普通的继承相比,匿名内部类有些局限性,因为它们要么是扩展一个类,要么是实现一个接口,但是两者不可兼得。
而且就算要实现接口,也只能实现一个。