0

I have gone through various sites to understand java does not support multiple inheritance. One of the reasons was to avoid issues like casting and constructor chaining. How does multiple inheritance would cause the issue of casting and constructor chaining in Java? Can anybody explain me with example.

Beast
  • 639
  • 2
  • 14
  • 29
  • If a class inherits from multiple classes, and each of those classes has a constructor, they must all run to initialize the subclass. – Dave Newton May 02 '14 at 01:11
  • But how does it creates casting problem ?Please explain with example – Beast May 02 '14 at 01:19
  • One of the reasons mentioned on those sites you mean. The only reason specifically mentioned in Arnold, Gosling, & Holmes, *The Java Programming Language* is diamond inheritance. I don't consider either casting or constructor chaining to be a major issue in implementing multiple inheritance. – user207421 May 02 '14 at 01:22

1 Answers1

0

There are multiple reasons why multiple inheritance could be an issue, and to prevent these, Java simply does not allow it at all. The main one is diamond inheritance aka the diamond problem. Lets say you have superclass animal, and subclasses land and water. Now, lets say you create another class, frogs. Because frogs can live in water, or on land, you decide that the frog class will inherent from both land and water. So it will be a subclass of land and water.

Lets extend our scenario to say that the animal class has a move method. This method has the animal traveling a distance without specifying how they do so. The land subclass overrides this move method to specify that the animal is walking. Meanwhile, the water subclass overrides to specify that the animal is swimming. If a frog were to try to move, it would not know whether it was swimming, or walking. This can cause some serious issues, and is the basic problem to which EJP was referring.