Search code examples
javainheritanceinterfacemultiple-inheritance

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


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?


Solution

  • 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();
        }
    }