【问题标题】:Anonymous inner class : Return an instance of an anonymous inner class匿名内部类:返回一个匿名内部类的实例
【发布时间】:2020-07-05 11:46:47
【问题描述】:

我正在通过《Thinking in java 4th Edition》这本书自学Java。

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

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\001. 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

我有什么想念的吗?

【问题讨论】:

  • 编译时Contents 类需要在编译器的类路径中。这可能意味着您正在同时编译包含它的文件;您可能需要告诉编译器在哪里可以找到已编译的类。没有更多细节,我们不能说。并且需要导入它不在同一个包中

标签: java inner-classes anonymous-class


【解决方案1】:

此匿名类声明创建一个匿名类,它是类Contents 的子类型。

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

【讨论】:

  • 如果在使用创建匿名类之前需要定义类,匿名类是什么意思
  • @tom 您不需要“定义”基类,您可以创建一个扩展Object 的匿名类。但是,基类未公开的任何方法或字段在编译时都会隐藏,因为您的类没有命名。它主要用于扩展已经存在的接口和抽象类,以便在 1 个变量中使用。这样您就可以快速实现具体实现。例如,研究如何实现迭代器。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-06
  • 1970-01-01
  • 1970-01-01
  • 2019-08-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多