Home > OS >  Java Enum can't extends other Enum, class can
Java Enum can't extends other Enum, class can

Time:02-03

User from Stackoverflow asked this question, unfortunately doesn't have answer which can explain situation.

Why enum can't extend another class while all other classes can

I have the same question. Java also tells that it is multyple extends and it is not supports. Java documentation.

But this part confusing me. If any class by default extends Object class(Main class in Java), and any new class can extend another class (except Object class), but any new Enum can't? Why?

Any Enum extends Enum class by default and for special for enum can't extend more classes, and if say it is program way, will be more understandable. But in documentation was writen can't extends because it is multyple classes. Maybe Documentation isn't correct? If someone can explain this part, please explain this.

Thank you!

CodePudding user response:

As the comments on the question you linked to explain, all classes do not extend Object.

A class:

class Foo { }

implicitly extends Object, but a class:

class Bar extends Foo { }

Just extends Foo.

It is also a descendant of Object via Foo.

So an enum implicitly extends Enum, and can't extend anything else.

Enums are final classes, so nothing can extend them.

CodePudding user response:

From the documentation you have linked:

Note: All enums implicitly extend java.lang.Enum. Because a class can only extend one parent (see Declaring Classes), the Java language does not support multiple inheritance of state (see Multiple Inheritance of State, Implementation, and Type), and therefore an enum cannot extend anything else.

Basically Enum has complier magic built in, that actually has the complier extend the Enum class from the java.lang.Enum. Java doesn't support multiple inheritance of classes and hence you cant have extended Enums.

See this from the spec jls-8.9 as well.

An enum type is implicitly final unless it contains at least one enum constant that has a class body.

It is a compile-time error to explicitly declare an enum type to be final.

  •  Tags:  
  • Related