Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
572 views
in Technique[技术] by (71.8m points)

java - How to create a class that "extends" two existing concrete classes

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 , class B and i need to create another class C which extends both A and B because C should have boths functionality and also note that A and B are not inter related so even i cant say A may extend class B.

I am quite confused what should i do right now. I know we cant change java... but at least there would be some way possible. Even the nearest may also do... please help me out.

Adding more details:- Class B is a standard API while class A is a common exception class that need to be inherited by all exception classes.

Related question:

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...