How to create a class that “extends” two existing concrete classes

后端 未结 8 2028
悲哀的现实
悲哀的现实 2020-12-19 20:36

I very well know that it can be done with the help of interfaces and i have done it many times. But this time my situation is quite difference. I have class A ,

相关标签:
8条回答
  • 2020-12-19 21:37

    A common oop principle is "choose composition over inheritance", since you can't extend 2 classes I would suggest having one of or both of those classes as members of Class C, that is of course if that works for what you are trying to do.

    0 讨论(0)
  • 2020-12-19 21:38

    This is typically solved using object composition.

    This is also advocated in Effective Java, Item 16: Favor composition over inheritance.

    Java restricts a class from having an is a-relation to two (unrelated) classes. It does not however restrict a class from having the functionality of two unrelated classes.


    class A {
        void doAStuff() {
            System.out.println("A-method");
        }
    }
    
    class B {
        void doBStuff() {
            System.out.println("B-method");
        }
    }
    
    // Wraps an A and a B object.
    class C {
        A aObj;
        B bObj;
    
        void doAStuff() {
            aObj.doAStuff();
        }
    
        void doBStuff() {
            bObj.doBStuff();
        }
    }
    

    (Alternatively you could have class C extends A and only create wrapper methods for B, but keep in mind that it should make sense to say C is an A.)


    I have a design pattern that need to be followed and for that its compulsory to extend

    This is, as you probably know completely impossible. You could however create proxy classes for A and B that delegate the functionality to the C-instance. For instance by adding these two methods to the C-class above:

    class C {
    
        // ...
    
        public A asAObject() {
            return new A() {
                @Override
                void doAStuff() {
                    C.this.doAStuff();
                }
            };
        }
    
        public B asBObject() {
            return new B() {
                @Override
                void doBStuff() {
                    C.this.doBStuff();
                }
            };
        }
    }
    
    0 讨论(0)
提交回复
热议问题