简体   繁体   中英

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

I am self-learning Java with the book "Thinking in java 4th Edition".

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

//: 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 .

Looking at the error, I assume that you do not have a named class called Contents defined anywhere. If you already have that class, then it may not have been imported properly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM