Bujanca Mihai Bujanca Mihai - 1 year ago 94
Java Question

Class extending more than one class Java?

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

and a class I created. Is this possible in Java? Both statements
class X extends TransformGroup extends Y
class X extends TransformGroup, Y
receive an error. And if it is not possible, why?
but I guess it also extends
since it inherits fields from
and it can be passed where a
object is required. Also, like all classes in Java, they extend
class. So why wouldn't it be possible to extend with more than one class?

TransformGroup inheritance

So, if that is possible, what is the proper way to do it? And if not, why and how should I solve the problem?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download