Why is it wrong to supply type parameter in the constructor of a generic class (Java)?

前端 未结 3 629
别那么骄傲
别那么骄傲 2021-01-15 16:00

I\'m just learning about generics in Java from a textbook, where it talks about a class GenericStack implemented with an ArrayList

3条回答
  •  长发绾君心
    2021-01-15 16:09

    There are two parts to this:

    1. The generic type parameter given for the class definition is available within the class itself.

    2. You can have generic types specific to individual methods (including constructor).

    Look at the following example:

    package snippet;
    
    import java.util.ArrayList;
    
    public class Y extends ArrayList {
    
        public  Y(T t) {
        }
    }
    

    Where as the type E is available to the whole of the class, the type T is valid only within the constructor.

提交回复
热议问题