I have two different classes:
class A<K,V> {
B b = new B;
public V get(K k) {
return b.get(k);
}
}
class B<K,V> {
V v;
public V get(K k) {
return v;
}
}
I get an incompatible types error in the get method of class A.
Does that mean type V of class A is not the same as type V of class B? In that case, how do I fix this issue? Can I simply typecast it to V before returning?
Parametrize B
with V
in A
. This way the compiler can be sure that your class B
will return an object of type V
.
class A<K,V> {
B<K,V> b = new B<K,V>;
public V get(K k) {
return b.get(k);
}
}
Change B b = new B;
inside class A
to B<K,V> b = new B<>();
This makes sure that the types referenced by K
and V
within the definition of B
for the variable b
match up with those within the definition of A
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.