匿名 class 作为 class 的成员

Anonymous class as member of class

我在一篇文章中找到了这个。它实现了 Parcelable 以在 Android

中的活动之间传递数据
public class Student implements Parcelable {

public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
    public Student createFromParcel(Parcel in) {
        return new Student(in);
    }

    public Student[] newArray(int size) {
        return new Student[size];
    }
};

private long id;
private String name;
private String grade;

// Constructor
public Student(long id, String name, String grade){
    this.id = id;
    this.name = name;
    this.grade = grade;
}

public long getId() {
    return id;
}

public void setId(long id) {
    this.id = id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getGrade() {
    return grade;
}

public void setGrade(String grade) {
    this.grade = grade;
}

// Parcelling part
   public Student(Parcel in){
       this.id = in.readLong();
       this.name = in.readString();
       this.grade =  in.readString();
   }

@Override
public int describeContents() {
    return 0;
}

@Override
   public void writeToParcel(Parcel dest, int flags) {
    dest.writeLong(this.id);
    dest.writeString(this.name);
    dest.writeString(this.grade);
   }

@Override
public String toString() {
    return "Student{" +
            "id='" + id + '\'' +
            ", name='" + name + '\'' +
            ", grade='" + grade + '\'' +
            '}';
}
}

在此示例中,声明并实现了一个字段 CREATOR Parcelable.Creator Interface.This 是一个匿名 class.Does 这意味着匿名 classes 也可以创建为成员class?而且我从其他渠道了解到Anonymous classes不能是static的,但是这里声明为static。我不明白这个 example.Can 中匿名 class 的上下文 有人解释一下吗?

Does this mean anonymous classes can also be created as members of a class?

您可以存储对字段的匿名 class 实例引用,是的。

and I have learnt from other sources that Anonymous classes cannot be static, but here it is declared as static

的确,匿名 classes 不能显式 static。但是它们可以在静态上下文中使用(如您发布的示例 - 初始化静态字段),这使它们隐式静态。 Java 语言规范在 15.9.2 中涵盖了这一点:

Let C be the class being instantiated, and let i be the instance being created. If C is an inner class, then i may have an immediately enclosing instance (§8.1.3), determined as follows:

If C is an anonymous class, then:

  • If the class instance creation expression occurs in a static context, then i has no immediately enclosing instance.

  • Otherwise, the immediately enclosing instance of i is this.