Why does the compiler generate enums in Java?

I really understand that it cannot extend any class to implement enumeration, because it means multiple inheritance But what I don't understand is why the enumeration class created by the compiler when using "enum" instead of "class" is final

Is there any reason why enumeration cannot be extended?

Also: is there a way to implement common behavior for different enumerations without copy & paste?

Solution

A very important aspect of enumeration is that numbers or values are known at compile time (at least at compile time)

So if you have such an enumeration:

public enum Foo {
  BAR,BAZ;
}

Then you know it has two values: bar and Baz

If you can extend enumeration, you can introduce an extended foo enumeration to add qux Now, since extended foo will be foo, qux will suddenly become a valid foo value Nothing prevents you from adding any additional foo values

This means that the compiler can no longer check whether your switch covers all foo cases Similar static analysis steps are no longer possible In fact, your enumeration will no longer be a special type, and the difference is small for ordinary classes with some predefined instances

Side note: the generated enumeration class is not always final: if (at least) one of your enumeration values has a value specific body, the "base" class will not be final, but the compiler will still prevent you from extending it

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>