4

If I have 4 distinct Java types (call them A B C D), and A is a subtype of B and A is a subtype of C and B is a subtype of D and C is a subtype of D, is this legal? Are there any examples out there?

Drawing the diagram:

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

So D is the supertype. Thanks!

pauliwago
  • 5,359
  • 10
  • 36
  • 48
  • 1
    No. Java does not support multiple inheritance, so `A` cannot be a subtype of both `B` and `C`. – RB. Feb 12 '13 at 09:14
  • 2
    Nope. Java supports only single inheritance. And that's a good thing :) The correct alternative is to use "interfaces". – paulsm4 Feb 12 '13 at 09:14

4 Answers4

6

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 a different thing from multiple inheritance.

So yes it's possible and for you to do this so far as you can check if something is an instance of an interface but this is not the same as a class type, and your diagram would look a tad different to the one you have drawn.

krystan honour
  • 5,934
  • 2
  • 31
  • 61
  • 1
    You're correct: interfaces *are* "a different thing from multiple inheritance". If the OP wants "A" to be a subtype of both "C" and "B" at the same time, then the answer is a definite "No". – paulsm4 Feb 12 '13 at 09:17
1

In java such diagram would only happen if D, C and B are all interfaces. This is legal and will work. An example - any class implementing two interfaces for instance Comparable. and Hashable. Object is a common ancestor of both these interfaces(though not direct).

Ivaylo Strandjev
  • 64,309
  • 15
  • 111
  • 164
1

is this legal?

Yup. Java doesn't support Multiple Inheritance with classes. Only Multilevel.

So, A can't inherit from both B and C, at a time.

See: Multiple Inheritance in java and How do Java Interfaces simulate multiple inheritance?

Community
  • 1
  • 1
Azodious
  • 13,385
  • 1
  • 32
  • 68
0

Java does not support multiple inheritance.

And why not? You can take a look here. The inheritance hierarchy which you shown is typical diamond problem.

Sam
  • 2,012
  • 4
  • 28
  • 42