Jevgenij Huebert
Jevgenij Huebert

Reputation: 21

Overload constructor with generic parameter type (extends vs. extends and Interface)

A is abstract

public <T extends A> B(T parameter) {
    //...do some stuff with A features
}
public <T extends A & I> B(T parameter) {
    //...do some stuff with A and I features
}

This code didn't work, because java says: Erasure of method B(T) is the same as another method in type B

But why? I don't understand. When I have an Object A take the first Construktor, when A implements I the other...

I mean you probably want say in this case A always implements I, but no:

look at this:

C1 extends A

C2 extends A

C3 extends A implements I

C1 and C2 would call first constructor and C3 second one. Why is this not possible?

I can not do this:

A is abstract

public B(A parameter) {
    //...do some stuff with A features
}
public B(I parameter) {
    //...do some stuff with I features
}

because if A implements I it allways will choose the first constructor. If you know another way to avoid this problem, please tell me.

Upvotes: 1

Views: 346

Answers (1)

Michael
Michael

Reputation: 44200

It's a legacy thing. See this question for the explanation: Method has the same erasure as another method in type

You can only really solve it by having two different factory methods with two different names:

class B {
    public static <T extends A> B create(T param) {
        return new B(/*...*/);
    }

    public static <T extends A & I> B createWithI(T param) {
        return new B(/*...*/);
    }

    private B(/*args*/) {
        //...
    }
}

or, as Khelwood suggested, using instanceof:

class B
{
    @SuppressWarnings("unchecked")
    public <T extends A, AI extends A & I> B(T param) {
        if (param instanceof I) {
            AI ai = (AI) param;
            // A and I
        }
        else {
            // Just A
        }
    }
}

Upvotes: 1

Related Questions