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

后端 未结 10 1004
隐瞒了意图╮
隐瞒了意图╮ 2020-11-29 00:48

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

10条回答
  •  旧时难觅i
    2020-11-29 01:15

    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)

提交回复
热议问题