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

后端 未结 10 1015
隐瞒了意图╮
隐瞒了意图╮ 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条回答
  •  北荒
    北荒 (楼主)
    2020-11-29 01:30

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

提交回复
热议问题