Search code examples
androidparcelableanonymous-class

Anonymous class as member of class


I have found this in an article. It implements Parcelable for passing data between activities in 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 + '\'' +
            '}';
}
}

In this example, a field CREATOR is declared and implements Parcelable.Creator Interface.This is an anonymous class.Does this mean anonymous classes can also be created as members of a class? and I have learnt from other sources that Anonymous classes cannot be static, but here it is declared as static. I don't understand the context of anonymous class in this example.Can someone explain this?


Solution

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

    You can store the anonymous class instance reference to a field, yes.

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

    It's true that anonymous classes cannot be explicitly static. But they can be used in a static context (as in the example you posted - initialising a static field) which makes them implicitly static. Java language spec covers this in 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.