[英]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\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
我想念什么嗎?
這個匿名 class 聲明創建了一個匿名 class ,它是 class Contents
的子類型。
查看錯誤,我假設您沒有在任何地方定義名為Contents
的名為 class 的名稱。 如果您已經擁有該 class,那么它可能沒有正確導入。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.