匿名内部 class : Return 匿名内部 class 的实例

Anonymous inner class : Return an instance of an anonymous inner class

我正在自学Java《思考java第4版》一书。

当我开始尝试书中的一个示例时,它给出了编译器错误。

https://github.com/BruceEckel/TIJ4-code/blob/master/examples/innerclasses/Parcel7.java

//: innerclasses/Parcel7.java
// Returning an instance of an anonymous inner class.

public class Parcel7 {
  public Contents contents() {
    return new Contents() { // Insert a class definition
      private int i = 11;
      public int value() { return i; }
    }; // Semicolon required in this case
  }
  public static void main(String[] args) {
    Parcel7 p = new Parcel7();
    Contents c = p.contents();
  }
} ///:~
.\Parcel7.java:4: error: cannot find symbol
    public Contents contents() {
           ^
  location: class Parcel7
.\Parcel7.java:5: error: cannot find symbol
        return new Contents() {
                   ^
  symbol:   class Contents
  location: class Parcel7
.\Parcel7.java:13: error: cannot find symbol
        Contents c = p.contents();
        ^
  symbol:   class Contents
  location: class Parcel7
3 errors
PS S:\Java Learning[=14=]1. Hello> javac .\Parcel7.java
.\Parcel7.java:2: error: cannot find symbol
    public Contents contents() {
           ^
  symbol:   class Contents
  location: class Parcel7
.\Parcel7.java:3: error: cannot find symbol
      return new Contents() { // Insert a class definition
                 ^
  symbol:   class Contents
  location: class Parcel7
.\Parcel7.java:10: error: cannot find symbol
      Contents c = p.contents();
      ^
  symbol:   class Contents
  location: class Parcel7
3 errors

我错过了什么吗?

此匿名 class 声明创建一个匿名 class,它是 class Contents.

的子类型

查看错误,我假设您没有在任何地方定义名为 Contents 的命名 class。如果您已经有了 class,那么它可能没有正确导入。