Home > Software design >  Static method with generic return type [duplicate]
Static method with generic return type [duplicate]

Time:10-07

I am trying to define a static method which can return childs of a specific class. I am using generics for that it is not working.

Example code:

public class Test {

    class A {
    }

    class B extends A {
    }

    public static <T extends A> T getA() {
        return new B();
    }

    public static void main(String[] args) {
        B b = getA();
    }
}

As you can see I am saying getA() will return T which is a child of the "A" class. I return B instance there, and it is a child of A but still it is not compiling. Any idea about what am I doing wrong? Thanks in advance!

Edit: And there would be multiple sub types to return from getA()

public class Test {

    class A {
    }

    class B extends A {
    }

    class C extends A {
    }

    public static <T extends A> T getA(int type) {
        if(type = 0) {
             return new B();
        } else {
             return new C();
        }
    }

    public static void main(String[] args) {
        B b = getA(0);
        C c = getA(1);
    }
}

CodePudding user response:

As you can see I am saying getA() will return T which is a child of the "A" class.

Yes, but you're allowing the caller to say which child class of A they want to have returned.

What if you wrote X x = getA();, where X is a subtype of A but not B?

The only thing you can safely return from that method is null.

If you want to say the method will return any subtype of A, make the return type A.

  • Related