Does Java Enum Classes by default extend Java Object Class?

588 views Asked by At

I have defined my own enum, which will extend Java Enum Class. Does Java Enum Class extend Java Object Class?

enum ORDER {
    FIRST,
    SECOND,
    THIRD,
    FOURTH
}
2

There are 2 answers

9
fhossfel On

Yes. A simple unit test can prove that the class hierarchy in your example is ORDER -> java.lang.Enum -> java.lang.Object:

public class EnumTest {

    enum ORDER {
    FIRST,
    SECOND,
    THIRD,
    FOURTH
    }

    @Test
    public void test() {

            
      System.out.println(ORDER.class.getSuperclass().getSuperclass());


    }

}

This will return

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running de.interassurance.service.EnumTest
class java.lang.Object
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.017 s - in de.interassurance.service.EnumTest

Results:

Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
3
Duloren On

Yes, in java any non-null is a reference for an instance of Object. In other words

aRef instanceof Object 

is true unless aRef is null regardless aRef type is an enum or a regular class.

Indeed, the enum keyword "defines a class (called an enum type). The enum class body can include methods and other fields. The compiler automatically adds some special methods when it creates an enum." https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html

Thus, references for enum types have the same elementary properties as other "regular" objects.

Thus, you can make calls like:

ORDER obj = ORDER.FIRST;
System.out.println(obj.hashCode());
System.out.println(obj.equals(otherObj));

in the same way as using an object of a non-enum class.