1
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.

  • 1
    See (for instance) [Type erasure - when and what happens](https://stackoverflow.com/questions/339699/java-generics-type-erasure-when-and-what-happens) – khelwood Jun 12 '18 at 10:58
  • 1
    Overloading is problematic with generics. You could use `if (parameter instanceof I)...` inside your constructor to customise its behaviour. – khelwood Jun 12 '18 at 11:01
  • my problem is, Im calling a super(params) and I have to write inline IFs... but I think its the way I should go. – Jevgenij Huebert Jun 15 '18 at 05:55

1 Answers1

1

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
        }
    }
}
Michael
  • 34,340
  • 9
  • 58
  • 100