Generics Java and Shadowing Type Parameters

This code is working fine

class Rule<T> { public <T>Rule(T t) { } public <T> void Foo(T t) { } } 
  • Does the method type parameter indicate a shadow class type parameter?
  • Also, when creating an object, the class type parameter is used?

Example

 Rule<String> r = new Rule<String>(); 

Does this usually apply to a class type parameter, in a situation where they do not conflict? I mean, when only a class has a type parameter and not a constructor, or does it look like a type parameter in a constructor? If they conflict , how will this change?

CM. DISCUSSION BELOW

if i have a function call

 x = <Type Parameter>method(); // this is a syntax error even inside the function or class ; I must place a this before it, why is this, and does everything still hold true. Why don't I need to prefix anything for the constructor call. Shouldn't Oracle fix this. 
+6
source share
2 answers

All your T different, but you can only see this if you call your methods using the full syntax :

For example, this code is valid:

 new <Float>Rule<Integer>().<Character>Foo(); 

To simplify the explanation, suppose your code is:

 class Rule<A> { public <B>Rule() { } public <C> void Foo() { } } 

You can then explicitly declare generic types such as:

 new <B>Rule<A>().<C>Foo(); 

If the types have the same name, the innermost one will be selected ( T for the method, not the class):

Using this code using parameters:

 class Rule<T> { public <T>Rule(T t) { } public <T> void Foo(T t) { } } 

Then this is true:

 new <Float>Rule<Integer>(3.2f); 

Note that T in the Float constructor, not Integer .

Another example:

 class Example<T> { public <T> void foo1() { // T here is the <T> declared on foo1 } public void foo2() { // T here is the <T> declared on the class Example } } 

I found another question related to method calls with explicit generic types without anything in front of them . It seems that static imports and method calls of the same class are the same. It seems that Java for some reason does not start the line with <Type> .

+7
source

Is the method type parameter a shadow parameter of the class type?

The constructor <T> declaration is not a class type. So yes, it obscures the class type parameter.

In this case, it is used as a parameter of a general type, which you can use with a constructor, for example, as an argument. Try this constructor:

 public <P> Rule(P arg1, P arg2) { } 

As you can see, I define the type <P> and then I use it to make sure that the arguments will be of type P In your case, you declare a type that will be valid for the constructor without using it.

Look at the page .

Also, when you create an object, does it use a class type parameter?

Each generic type definition has scope as a variable. Thus, a valid class type is returned from the constructor.

+1
source

Source: https://habr.com/ru/post/913182/


All Articles