[Java] Why no compilation error occurs for classes that do not implement Comparable

When handling a class that does not implement Comparable with TreeSet etc., it is specified that a runtime error (ClassCastException) is thrown instead of a compile error. This is thought to assume a scene where the parent class does not implement the Comparable interface and the child class implements Comparable when using generics.

Example

The Musician parent class does not implement Comapable, but the child class does.


class Musician {

    public enum Category {
        ROCK, JAZZ, CLASSIC
    }

    public String getName() {
        return name;
    }

    public Category getCategory() {
        return category;
    }

    private String name;
    private Category category;

    Musician(String name, Category category) {
        this.name = name;
        this.category = category;
    }
}

class ChildMusician extends Musician implements Comparable {

    ChildMusician() {
        super("", null);
    }

    @Override
    public int compareTo(Object o) {
        return 0;
    }
}

Run


Set<Musician> musicianSet = new TreeSet<>();
musicianSet.add(new ChildMusician());

If there is no child class, it would be more efficient to issue a compile error on the first line, but since there may be child classes, the cast is checked at runtime.

Recommended Posts

[Java] Why no compilation error occurs for classes that do not implement Comparable
Rails <% = expression%> Why no error occurs when empty
[Java] Explains ConcurrentModificationException that occurs in java.util.ArrayList for newcomers
Java reserved word summary that you do not know unexpectedly