Home > Net >  How can I return an empty parameterised class Box?
How can I return an empty parameterised class Box?

Time:06-24

I am learning generics in Java. How can I return an empty parameterised class Box in the method getBox? Thanks for helping.

public static <T> class Box<T> {
    private  T object;
    
    public static <T>Box<T> getBox() {   
        return new Box<T>();        
    }
}

CodePudding user response:

Remove the <T> before the keyword class, but keep the <T> after the class name.

There is a difference in declaring the type parameter for classes and declaring the type parameter for methods. For the generic method getBox, you declared the type parameter, correctly, before the return type, even if most people put a space between the type declaration and the return type. But for a generic class, the <T> after the class name declares type parameter T; any <T> before the class name is a syntax error.

  • Related