This code seems to work fine
class Rule
{
public Rule(T t)
{
}
public void Foo(T t)
{
}
}
All of your T
s are different, but you can only see it if you call your methods with the complete syntax:
For example, this code is valid:
new <Float>Rule<Integer>().<Character>Foo();
Just to make this easier to explain, let's assume your code is this:
class Rule<A>
{
public <B>Rule()
{
}
public <C> void Foo()
{
}
}
Then you can explicitly declare generic types like:
new <B>Rule<A>().<C>Foo();
If the types have the same name, the inner-most one will be chosen (the T
on the method, not the class):
With this code, taking parameters:
class Rule<T>
{
public <T>Rule(T t)
{
}
public <T> void Foo(T t)
{
}
}
Then this is valid:
new <Float>Rule<Integer>(3.2f);
Note that T
in the constructor is Float
, 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 that deals with calling methods with explicit generic types without something before them. It seems like static imports and same-class method calls are the same. It seems like Java doesn't let you start a line with <Type>
for some reason.
Does the method type parameter shadow the class type parameter?
The <T>
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 <P> Rule(P arg1, P arg2) {
}
As you can see I define a type <P>
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.