The type parameter E is hiding the type E. Generics template to a class

两盒软妹~` 提交于 2021-01-28 02:05:39

问题


I am practicing generics and i did the following.

Created a class called man as below.

public class Man{
int hands=2;
int legs=2;
boolean alive;

public Man(boolean b) {
    // TODO Auto-generated constructor stub
    alive=b;
}

}

created a class called person

public class Person<Man> {
Man p;
String name;


public Person(Man p, String name) {
    this.p = p;
    this.name = name;
}
public Person() {
    // TODO Auto-generated constructor stub
}

}

tried to instantiate a person of type string or int as below and it dosent throw an error.

Person<String> p1 = new Person<String>(new String("test"), "test1");
    Person<Integer> p2=new Person<>(1,"test");

when i checked carefully, i got the following warning. "The type parameter Man is hiding the type Man"

So i understand that giving Man as a type parameter to the class Person is as good as giving 'E' in java examples. Its not Man.class. Why did this happen? How do i assign my Man.class as the generic type parameter?

and can you throw me some good questions/practice exercises to learn generics.


回答1:


Because Man is the name of a class in the same package. Just change the name of your generic from Person<Man> to Person<T> or something else that doesn't resemble nor Man nor any other class.

More about generics:

  • Java Tutorials. Lesson: Generics (Updated)

Looks like you want that Person has only Man attribute using generics. You will need for that to have a super class that defines the generic and Person will inherit from it defining that it uses Man as the class used. Short example:

public abstract class AliveBeing<T> {
    protected T livingBeing;
    public AliveBeing(T livingBeing) {
        this.livingBeing = livingBeing;
    }
}

public class Person extends AliveBeing<Man> {
    //now your livingBeing field is from Man type...
    public Person(Man man) {
        super(man);
    }
}

This will make it but IMO this design is odd. It would be better to explain more about your current problem to get a better and accurate answer.

Note the difference:

//case 1
public class Foo<T> {
    //...
}

//case 2
public class Bar<E> extends Foo<E> {
    //...
}

//case 3
public class Baz extends Foo<String> {
    //...
}

In first case, Foo uses a generic class and you can refer to this class by T. In second case, Bar extends from Foo and declares using its own generic class and you can refer to it by E, but this E will be the same generic used from Foo (instead of T it will be E). In third case, Baz class extends from Foo but it won't define any generic behavior, instead it declares that the generic class used from Foo is String.



来源:https://stackoverflow.com/questions/19761890/the-type-parameter-e-is-hiding-the-type-e-generics-template-to-a-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!