[英]Type inference of constructor is throwing error when class has Type parameter
New to Generics concept and I am facing issue in below code泛型概念的新手,我在下面的代码中遇到了问题
public class Main
{
static class GenericCheck<X>{
private X x;
<T> GenericCheck(T t){
x=t;
System.out.println(t);
}
public void display(){
System.out.println(x);
}
}
public static void main(String[] args) {
GenericCheck<String> genericCheck = new GenericCheck("sathish worked");
}
}
Error throwing:错误抛出:
Main.java:14: error: incompatible types: T cannot be converted to X
x=t;
Can anyone please help me on this issue.任何人都可以在这个问题上帮助我。 Thanks in advance.
提前致谢。
Since there's nothing relating T
to X
, there's no way for the compiler to know they're related to one another.由于
T
与X
没有任何关系,编译器无法知道它们彼此相关。
It's not clear what you're trying to do with T
, X
is sufficient:不清楚你想用
T
做什么, X
就足够了:
public class Main
{
static class GenericCheck<X>{
private X x;
GenericCheck(X t){ // *** Use `X` directly
x=t;
System.out.println(t);
}
public void display(){
System.out.println(x);
}
}
public static void main(String[] args) {
GenericCheck<String> genericCheck = new GenericCheck<>("sathish worked");
// Need to provide generic here too ----------------^^ That shorthand form is fine
}
}
But if you want T
, it will need to be related to X
in some way, for example:但是如果你想要
T
,它需要以某种方式与X
相关,例如:
public class Main
{
static class GenericCheck<X>{
private X x;
<T extends X> GenericCheck(T t){
//^^^^^^^^^^
x=t;
System.out.println(t);
}
public void display(){
System.out.println(x);
}
}
public static void main(String[] args) {
GenericCheck<String> genericCheck = new GenericCheck<>("sathish worked");
// -------------------------------------------------^^
}
}
...but there's no reason to do that unless you have some other constraint on T
, since you can already provide a subclass of X
during construction with the class in the first code block above. ...但没有理由这样做,除非您对
T
有一些其他约束,因为您已经可以在构造期间使用上面第一个代码块中的类提供X
的子类。 This works fine, for instance:这工作正常,例如:
class Base {
}
class Derived extends Base {
}
public class Example
{
static class GenericCheck<X>{
private X x;
GenericCheck(X t){
x=t;
System.out.println(t.getClass().getName());
}
public void display(){
System.out.println(x);
}
}
public static void main(String[] args) {
GenericCheck<Base> genericCheck = new GenericCheck<>(new Derived());
}
}
JVM can not do x=t if there is not any relationship declared.如果没有声明任何关系,JVM 不能执行 x=t。 You can override the error though with explicit casting like
您可以使用显式转换来覆盖错误,例如
x=(Object)T;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.