How can interfaces replace the need for multiple inheritance when have existing classes

33,602

Solution 1

You should probably favor composition (and delegation) over inheritance :

public interface TaggedInterface {
    void foo();
}

public interface XMLElementInterface {
    void bar();
}

public class Tagged implements TaggedInterface {
    // ...
}

public class XMLElement implements XMLElementInterface {
    // ...
}

public class TaggedXmlElement implements TaggedInterface, XMLElementInterface {
    private TaggedInterface tagged;
    private XMLElementInterface xmlElement;

    public TaggedXmlElement(TaggedInterface tagged, XMLElementInterface xmlElement) {
        this.tagged = tagged;
        this.xmlElement = xmlElement;
    }

    public void foo() {
        this.tagged.foo();
    }

    public void bar() {
        this.xmlElement.bar();
    }

    public static void main(String[] args) {
        TaggedXmlElement t = new TaggedXmlElement(new Tagged(), new XMLElement());
        t.foo();
        t.bar();
    }
}

Solution 2

Actually, I have no good answer other than Java SHOULD have Multiple Inheritance. The whole point that interfaces should be able to replace the need for Multiple Inheritance is like the big lie that when repeated enough times becomes true.

The argument is that Multiple Inheritance causes all these problems (la-di-dah), yet I keep hearing those arguments from Java developers who have never used C++. I also don't EVER remember C++ programmers saying "Gee, I love C++, but if they would only get rid of Multiple Inheritance, it would become a great language". People used it when it was practical and didn't when it wasn't.

Your problem is a classic case of where Multiple Inheritance would be appropriate. Any suggestion to refactor the code is really telling you how to work around the PROBLEM that Java has no Multiple Inheritance.

Also all the discussion that "oh, delegation is better, la-di-dah" is confusing religion with design. There is no right way. Things are either more useful or less useful and that is all.

In your case Multiple Inheritance would be more useful and a more elegant solution.

As far as refactoring your code into a less useful form to satisfy all the religious people who have never used Multiple Inheritance and believe "Multiple Inheritance is bad", I guess you will have to downgrade your code because I don't see Java "improving" in that way any time soon. There are too many people repeating the religious mantra to the point of stupidity that I can't see it ever being added to the language.

Actually, my solution for you would be "x extends Tagged, XMLElement" and that would be all.

...but as you can see from the solutions provided above, most people think that such a solution would be WAY TOO COMPLEX AND CONFUSING!

I would prefer to venture into the "x extends a,b" territory myself, even if it is a very frightening solution that might overwhelm the abilities of most Java programmers.

What is even more amazing about the solutions suggested above is that everyone here who suggested that you refactor your code into "delegation" because Multiple Inheritance is bad, would, if they were confronted with the very same problem, would solve the problem by simply doing: "x extends a,b" and be done with it, and all their religious arguments about "delegation vs inheritance" would disappear. The whole debate is stupid, and it only being advanced by clueless programmers who only demonstrate how well they can recite out of a book and how little they can think for themselves.

You are 100% correct that Multiple Inheritance would help, and no, you are doing anything wrong in your code if you think Java should have it.

Solution 3

Similar to what Andreas_D suggested but with the use of inner classes. This way you indeed extend each class and can override it in your own code if desired.

interface IBird {
    public void layEgg();
}

interface IMammal {
    public void giveMilk();
}

class Bird implements IBird {
    public void layEgg() {
        System.out.println("Laying eggs...");
    }
}

class Mammal implements IMammal {
    public void giveMilk() {
        System.out.println("Giving milk...");
    }
}

class Platypus implements IMammal, IBird {

    private class LayingEggAnimal extends Bird {}
    private class GivingMilkAnimal extends Mammal {}

    private LayingEggAnimal layingEggAnimal = new LayingEggAnimal();

    private GivingMilkAnimal givingMilkAnimal = new GivingMilkAnimal();

    @Override
    public void layEgg() {
        layingEggAnimal.layEgg();
    }

    @Override
    public void giveMilk() {
        givingMilkAnimal.giveMilk();
    }
}

Solution 4

First it makes no sense to put the real implementation in all data classes since it is the same every time but this would be necessary with interfaces (I think).

How about using aggregation for the tags?

  1. Rename your Tagged class to Tags.

  2. Create a Tagged interface:

    interface Tagged { Tags getTags(); }

  3. Let each class that needs to be "tagged", implement Tagged and let it have a tags field, which is returned from getTags.

Second I don't see how I could change one of my inheritance classes to an interface. I have variables in here and they have to be exactly there.

That's right, interfaces can't have instance variables. The data structures storing the tags however, shouldn't necessarily IMO be part of the classes that are tagged. Factor out the tags in a separate data structure.

Solution 5

I'd solve it that way: extract interfaces for the Tagged and XMLElement class (maybe you don't need all methods in the public interface). Then, implement both interfaces and the implementing class has a Tagged (your actual concrete Tagged class) and an XMLElement (your actual concrete XMLElement class):

 public class MyClass implements Tagged, XMLElement {

    private Tagged tagged;
    private XMLElement xmlElement;

    public MyClass(/*...*/) {
      tagged = new TaggedImpl();
      xmlElement = new XMLElementImpl();
    }

    @Override
    public void someTaggedMethod() {
      tagged.someTaggedMethod();
    }
  }

  public class TaggedImpl implements Tagged {
    @Override
    public void someTaggedMethod() {
      // so what has to be done
    }
  }

  public interface Tagged {
     public void someTaggedMethod();
  }

(and the same for XMLElement)

Share:
33,602
fpdragon
Author by

fpdragon

Updated on July 09, 2022

Comments

  • fpdragon
    fpdragon almost 2 years

    First of all... Sorry for this post. I know that there are many many posts on stackoverflow which are discussing multiple inheritance. But I already know that Java does not support multiple inheritance and I know that using interfaces should be an alternative. But I don't get it and see my dilemma:

    I have to make changes on a very very large and complex tool written in Java. In this tool there is a data structure built with many different class objects with a linked member hierarchy. Anyway...

    • I have one class Tagged which has multiple methods and returns an object tag depending on the object's class. It needs members and static variables.
    • And a second class called XMLElement allows to link objects and in the end generate a XML file. I also need member and static variables here.
    • Finally, I have these many many data classes which nearly all should extend XMLElement and some of them Tagged.

    Ok ok, this won't work since it's only possible to extend just one class. I read very often that everything with Java is ok and there is no need for having multiple inheritance. I believe, but I don't see how an interface should replace inheritance.

    1. It makes no sense to put the real implementation in all data classes since it is the same every time but this would be necessary with interfaces (I think).
    2. I don't see how I could change one of my inheritance classes to an interface. I have variables in here and they have to be exactly there.

    I really don't get it so please can somebody explain me how to handle this?

  • giannis christofakis
    giannis christofakis over 11 years
    Can I ask one silly question?Where is the constructor to the above TaggedXmlElement class?
  • JB Nizet
    JB Nizet over 11 years
    Now it's there. Thanks for noticing.
  • fhucho
    fhucho almost 11 years
    This should be the top answer :)
  • Kemal Erdogan
    Kemal Erdogan over 10 years
    amen! and the is true for bloody c# and .net folks. Bertrand Meyer once said that the only reason .net and java does not have multiple inheritance is difficulty of writing a class loader that would support multiple bases classes.
  • supercat
    supercat over 10 years
    @KemalErdogan: In C++, can you cast any pointer directly to a top-level object type and then downcast directly to its actual type or any supertype thereof? Such ability, and the fact that upcasts and downcasts are identity-preserving, is fundamental to the design of Java.
  • h9uest
    h9uest over 9 years
    This answer is biased and may well be wrong in this particular case. 'Your problem is a classic case of where Multiple Inheritance would be appropriate.' --- Firstly you're not really sure what the problem is with the few lines of description. Secondly, the problem doesn't sound like a a classic case at all. Rule 2(parashift.com/c++-faq/mi-disciplines.html) comes with good reasons. Tagged and XMLElement don't sound like ABC's at all. Effectively, a proper C++ multiple inheritance paradigm has the idea of implementing multiple interfaces in the first place.
  • Steven Bluen
    Steven Bluen almost 8 years
    To support this answer, propriety code may expect your objects to be instances of a specific class. If two pieces of proprietary code expect the same object to be of two classes, neither an instance of the other, the only choices may be to use an extremely ugly hack of substituting interfaces for classes while hoping all the methods are compatible.