Today, I was just curious about why an enum can not extend anything else. I took a look on the Oracle document here, and I found the answer is below:
"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."
I have been learned of it before. But, wait a sec...! Why Java does not support multiple inheritance of state?
Since I have worked with other programming languages like C++, I was able to make a class extend some other classes.
The short answer is to avoid the issues of multiple inheritance of state. I wonder if other programming languages have these below terms but Java does.
The short answer is to avoid the issues of multiple inheritance of state. I wonder if other programming languages have these below terms but Java does.
Multiple inheritance of state
It is the ability to inherit fields from multiple classes. There is a problem and Java avoids it.
"For example, suppose that you are able to define a new class that extends multiple classes. When you create an object by instantiating that class, that object will inherit fields from all of the class's superclasses. What if methods or constructors from different superclasses instantiate the same field?"
Multiple inheritance of implementation
It is the ability to inherit method definitions from multiple classes.
There is a similar problem that sometimes compiler cannot determine which member or method to access or invoke. Java deals with that problem as below.
There is a similar problem that sometimes compiler cannot determine which member or method to access or invoke. Java deals with that problem as below.
"As with multiple inheritance of implementation, a class can inherit different implementations of a method defined (as default or static) in the interfaces that it extends. In this case, the compiler or the user must decide which one to use."
I just did a quick test for the above explaination
I just did a quick test for the above explaination
Conclusion, Java supports multiple inheritance of implementation but multiple inheritance of state.
Reference
[1]. https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html
[2]. https://docs.oracle.com/javase/tutorial/java/IandI/multipleinheritance.html
Comments
Post a Comment