0

i am using spring & have 2 interfaces,

interface A {
    public void a();
}

interface B {
    public void B();
}

and their implementations

class AImpl implements A {
    public void a(){ // TODO }
}
class BImpl implements B {
    public void b(){ // TODO }
}

Now I create an interface C

    interface C extends A, B {}

Is there any way I can get a bean of type C with method definations of AImpl & BImpl

1 Answer 1

1

You can't make a CImpl that extends AImpl and BImpl as Java doesn't support multiple inheritance for classes.

But you can do something like this:

class CImpl implements C {
    private A a;
    private B b;

    public CImpl(A a, B b) {
        this.a = a;
        this.b = b;
    }

    public void a() {
        a.a();
    }

    public void b() {
        b.b();
    }
}

And create your CImpl with:

CImpl c = new CImpl (new AImpl(), new BImpl());

If you use Spring (as your tags imply) you can configure AImpl, BImpl and CImpl as Beans and use autowiring for the constructor of CImpl.

Sign up to request clarification or add additional context in comments.

1 Comment

I understand that we cannot extend the implementations directly ( as there are multiple ). But since I have already provided implementations of these interfaces (A & B), is it not possible for spring to create an object of C. This is how it happens when you create custom repository in spring jpa.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.