Shadow of generic Java and type parameters

This code seems to work properly

class Rule<T>
{

    public <T>Rule(T t)
    {

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

    }
 }

>Does the method type parameter affect the class type parameter? > In addition, when you create an object, does it use the type parameters of the class?

example

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

This usually applies to type parameters of classes, if they do not conflict? I mean when only a class has a type parameter instead of a constructor, or does this look for a type parameter in the constructor? If they conflict, how will this change?

See the 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.

Solution

All your ts are different, but you can only see it if you call your method with complete syntax:

For example, this code is valid:

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

To make this easier to explain, let's assume that your code is like this:

class Rule<A>
{

    public <B>Rule()
    {

    }
    public <C> void Foo()
    {

    }
 }

Then you can explicitly declare generic types, such as:

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

If the type has the same name, the innermost type (t on the method, not the class) is selected:

Using this code, 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 problem involving calling methods with explicit generic types without something before them It seems that static import is the same as similar method calls It seems that Java does not allow you to start a line with < type > For some reason

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>