[英]Anonymous inner class : Return an instance of an anonymous inner class
I am self-learning Java with the book "Thinking in java 4th Edition".我正在自学Java这本书《思考java第4版》。
When i come to trying one example from the book, it gives compiler error.当我开始尝试书中的一个示例时,它会给出编译器错误。
https://github.com/BruceEckel/TIJ4-code/blob/master/examples/innerclasses/Parcel7.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
Do I miss anything?我想念什么吗?
This anonymous class declaration creates an anonymous class that is a sub-type of the class Contents
.这个匿名 class 声明创建了一个匿名 class ,它是 class
Contents
的子类型。
Looking at the error, I assume that you do not have a named class called Contents
defined anywhere.查看错误,我假设您没有在任何地方定义名为
Contents
的名为 class 的名称。 If you already have that class, then it may not have been imported properly.如果您已经拥有该 class,那么它可能没有正确导入。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.