I know that a class can implement more than one interface, but is it possible to extend more than one class? For example I want my class to extend both TransformGroup
and a class I created. Is this possible in Java? Both statements class X extends TransformGroup extends Y
and class X extends TransformGroup, Y
receive an error. And if it is not possible, why? TransformGroup
extends Group
but I guess it also extends Node
since it inherits fields from Node
and it can be passed where a Node
object is required. Also, like all classes in Java, they extend Object
class. So why wouldn't it be possible to extend with more than one class?
So, if that is possible, what is the proper way to do it? And if not, why and how should I solve the problem?
In Java multiple inheritance is not permitted. It was excluded from the language as a design decision, primarily to avoid circular dependencies.
Scenario1: As you have learned the following is not possible in Java:
public class Dog extends Animal, Canine{
}
Scenario 2: However the following is possible:
public class Canine extends Animal{
}
public class Dog extends Canine{
}
The difference in these two approaches is that in the second approach there is a clearly defined parent or super
class, while in the first approach the super
class is ambiguous.
Consider if both Animal
and Canine
had a method drink()
. Under the first scenario which parent method would be called if we called Dog.drink()
? Under the second scenario, we know calling Dog.drink()
would call the Canine
classes drink
method as long as Dog
had not overridden it.