How do I create an instance? Include code

The compiler will not allow me to save <X, Y> in the last line, and I do not understand why.

How do I get such a general construct for compilation?

I tried changing the code to this:

X a = new A<X,Y>(); // "Type mismatch: cannot convert from A<X,Y> to X" Y b = new B<X,Y>(); // "Type mismatch: cannot convert from B<X,Y> to Y" W<X,Y> s = new M<X,Y>(a,b); // no error 

I'm a little lost - please help!

+4
source share
3 answers

The constructor M< X, Y > expects to get X and a Y , but you are trying to give it IA< X, Y > and IB< X, Y > . Necessary relationships are reversed; X is IA< X, Y > , but not vice versa, and similarly for Y

The following compilations, but apparently not restrictive enough for what you need:

 class A<X extends IA<X,Y>, Y extends IB<X,Y>> implements IA<X,Y>{} class B<X extends IA<X,Y>, Y extends IB<X,Y>> implements IB<X,Y>{} interface IA<X extends IA<X,Y>, Y extends IB<X,Y>> {} interface IB<X extends IA<X,Y>, Y extends IB<X,Y>> {} class M<X extends IA<X,Y>, Y extends IB<X,Y>> extends W<X,Y>{ public M(IA<X,Y> x, IB<X,Y> y){} // this is the only change } class W<X extends IA<X,Y>, Y extends IB<X,Y>> {} //To my check class code: public <X extends IA<X,Y>, Y extends IB<X,Y>> void check() { IA<X,Y> a = new A<X,Y>(); IB<X,Y> b = new B<X,Y>(); W<X,Y> s = new M<X,Y>(a,b); } 
+4
source

The question includes many common limitations that do not make sense. The constructor M<X,Y> accepts arguments of types X and Y , which are parameters of the type of the general check method (this means that the caller can decide that X and Y are anything, and this is necessary for work). So why do you expect a and b (or something else in this case) to be the correct type?

If you want to ask how to change the generics restrictions so that it works, here is much simpler (it just changes the generics (but keeps W and M as they are) and nothing more from the original) which compiles and is probably closer to what you wanted in any case:

 public interface IA<X, Y> {} public interface IB<X, Y> {} public class A implements IA<A,B>{} public class B implements IB<A,B>{} public class M<X extends IA<X,Y>, Y extends IB<X,Y>> extends W<X,Y>{ public M(X x, Y y){} } public class W<X extends IA<X,Y>, Y extends IB<X,Y>> {} //To my check class code: public void check() { A a = new A(); B b = new B(); W<A,B> s = new M<A,B>(a,b); } 
+1
source

Although I saw that you do not want to do this:

 @SuppressWarnings("unchecked") W<X,Y> s = new M<X,Y>((X) a,(Y) b); 

works.

As Judge Mental said, your problem is too abstract, and it is difficult for us to provide meaningful assistance. For example, in the check method, you create new A<X,Y>() . What does it mean? You do not define X and Y In real code, there will never be such a method.

0
source

All Articles