Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inherit from multiple base classes in Java? [duplicate]

Possible Duplicates:
Cheat single inheritance in Java !!
Why is Multiple Inheritance not allowed in Java or C#?
Multiple Inheritance in java.

I know that we can use interfaces to inherit from multiple classes but is it possible to inherit the state as well?
How can I inherit methods with definitions from 2 classes and have them in a third class in Java?

like image 207
Anonymous Avatar asked Jan 09 '10 00:01

Anonymous


People also ask

Can you inherit from multiple classes in Java?

Unlike some other popular object oriented programming languages like C++, java doesn't provide support for multiple inheritance in classes.

Can a class inherit from multiple base classes?

You can derive a class from any number of base classes. Deriving a class from more than one direct base class is called multiple inheritance. The order of derivation is relevant only to determine the order of default initialization by constructors and cleanup by destructors.

Can a same interface be inherited by 2 different classes?

A class can implement multiple interfaces and many classes can implement the same interface.

How does inheritance avoid duplication Java?

- [Instructor] In Java, we can achieve inheritance by using the keyword extends. The subclass will use this keyword with the superclass in its class definition to inherit all the properties and behaviors of the superclass.


3 Answers

Multiple inheritance is not allowed in Java. Use delegates and interfaces instead

public interface AInterface {
        public void a();
}
public interface BInterface {
    public void b();
}

public class A implements AInterface {
    public void a() {}
}
public class B implements BInterface {
    public void b() {}
}

public class C implements AInterface, BInterface {
    private A a;
    private B b;

    public void a() {
        a.a();
    }
    public void b() {
        b.b();
    }
}

Since Java 8 it's possible to use Default Methods in Interfaces.

like image 53
Fabiano Avatar answered Nov 07 '22 20:11

Fabiano


Short answer: You can't. Java only has multiple inheritance of interfaces.

Slightly longer answer: If you make sure the methods you care about are in interfaces, then you can have a class that implements the interfaces, and then delegates to instances of the "super classes":

interface Noisy {
  void makeNoise();
}


interface Vehicle {
  void go(int distance);
}

class Truck implements Vehicle {
  ...
}

class Siren implements Noisy {
  ...
}

class Ambulance extends Truck implements Noisy {
  private Siren siren = new Siren();

  public makeNoise() {
    siren.makeNoise();
  }

  ...
}
like image 26
Laurence Gonsalves Avatar answered Nov 07 '22 22:11

Laurence Gonsalves


You can not, Java doesn't support multiple inheritance. What you could do is composition.

like image 3
albertein Avatar answered Nov 07 '22 21:11

albertein