How do I subclass an AutoValue class How do I subclass an AutoValue class

How do I subclass an AutoValue class ?

AutoValue is a powerful tool for generating Parcelable Android classes, but subclassing comes with its own set of challenges. The official documentation clearly states that extending one @AutoValue class with another is not supported, citing issues related to the general contract of overriding equals.

In situations where you need to create a subclass with additional fields, the recommended approach is to favor composition over inheritance. As stated in the documentation, “If you have common fields, you can put them in an interface that both implementations implement.”

Let’s delve into a practical example to illustrate the process. Consider the following @AutoParcelGson class named User:


@AutoParcelGson
public abstract class User implements Parcelable {

    public abstract String username();

    public static User create(String username) {
        return builder().username(username).build();
    }

    public static Builder builder() {
        return new AutoParcelGson_User.Builder();
    }

    @AutoParcelGson.Builder
    public interface Builder {
        Builder username(String username);
        User build();
    }
}
        

Now, the goal is to create another @AutoValue class called Customer with additional fields. However, due to AutoValue limitations, direct subclassing is not an option.

The recommended approach to achieve this is by creating a new class, say BetterUser, which does not extend User but rather contains a field of type User. This way, you can define the behavior of BetterUser without impacting other classes.

Here’s a snippet to illustrate the concept:


public class BetterUser {
    private final User user;
    private final String additionalField;

    public BetterUser(User user, String additionalField) {
        this.user = user;
        this.additionalField = additionalField;
    }

    // Additional methods for BetterUser
}
        

This approach adheres to the principles outlined in Effective Java, avoiding issues related to equals symmetry and providing a consistent solution for extending AutoValue classes.

Conclusion

While direct subclassing of AutoValue classes is not supported, employing composition and creating new classes with the necessary fields allows you to achieve the desired functionality without violating fundamental principles. Always prioritize code consistency and best practices for a robust and maintainable codebase.