Generics Java and Shadowing of type parameters

前端 未结 2 967
梦毁少年i
梦毁少年i 2020-12-16 04:54

This code seems to work fine

class Rule
{

    public Rule(T t)
    {

    }
    public  void Foo(T t)
    {

    }
 }
         


        
2条回答
  •  误落风尘
    2020-12-16 05:38

    Does the method type parameter shadow the class type parameter?

    The declaration on constructor is not referred to class type. So yes, it shadow the class type parameter.

    In this case it is used as a generic type param that you can use with the constructor, for example as argument. Try this constructor:

    public 

    Rule(P arg1, P arg2) { }

    As you can see I define a type

    and then I use it to be sure that the arguments will be of type P. In your case you are declaring a type that will be valid for the constructor without using it.

    Look at this page.

    Also when you create an object does it use the type parameter of the class?

    Every generic type definition has is scope as a variable. So out of the constructor returns valid the class type.

提交回复
热议问题