Subtypes in java

If I have 4 different Java types (name them A B C D

) and A

is subtype B

and A

is subtype C

and B

is subtype D

and C

is subtype D

, is that legal? Are there examples?

Drawing diagram:

           D
          | |  
        |     |
       B       C
        |     |
          | |
           A

      

So D is a supertype. Thank!

+3


source to share


4 answers


This is not legal with inheritance as Java as a language does not support multiple inheritance.

However, you can do this by implementing multiple interfaces, which is different from multiple inheritance.



So yes, it is possible for you to do this as well, as long as you can check if something is an instance of the interface, but that is not the same as the class type and your diagram will be slightly different from the one you draw.

+6


source


In java, such a diagram would only happen if D, C and B are all interfaces. This is legal and will work. An example is any class that implements two interfaces, eg Comparable

. and Hashable

. The object is a common ancestor of both of these interfaces (although not direct).



+1


source


is it legal?

Uh-huh. Java does not support multiple inheritance with classes. Only multilevel.

So, A

can not inherit from both B

, and on C

at a time.

See: Multiple inheritance in java and How do Java interfaces mimic multiple inheritance?

+1


source


Java does not support multiple inheritance.

Why not? You can take a look here . The inheritance hierarchy you found is a typical problem with diamonds.

0


source







All Articles