当从通用类类型/形式类型参数 T/E
继承时,使用有效的类类型/实际类型参数,例如 Type/String
,会出现许多组合,这很容易造成困惑。不知道该选择哪个以及何时使用?
public class SubClass<T> implements SuperIfc<T> <-- It is straight forward to understand
public class SubClass<T> implements SuperIfc<Type>
public class SubClass<Type> implements SuperIfc<T>
public class SubClass<Type> implements SuperIfc<Type>
public class SubClass<Type> implements SuperIfc
public class SubClass implements SuperIfc<Type>
public class SubClass implements SuperIfc<T> <--- Hope we cannot declare <T> in his case while initialising SubClass.
// Bounded type parameter
public class SubClass<T extends Type> implements SuperIfc<Type>
public class SubClass<T extends Type> implements SuperIfc<T> <-- Looks <T> at SuperIfc also refers <T extends Type>, and no need to declare it again at SuperIfc.
// Recursive type bound
public class SubClass<T extends Comparable<T>>> implements SuperIfc<T>
public class SubClass<T extends Comparable<T>>> implements SuperIfc<Type>
为了更清晰地解决“在子类化时不兼容类型”的问题。
案例一:
public class Test {
interface TestIfc {
public static <T extends TestIfc> T of(int choice) {
if(choice == 1) {
return new TestImpl(); <-- PROB_1: incompatible type error
} else {
return new SomeOtherTestImpl(); //incompatible type error
}
}
}
static class TestImpl implements TestIfc {}
static class SomeOtherTestImpl<T extends TestIfc> implements TestIfc {
//The below method also having same error though with declaration
public T of() {
return new TestImpl(); <-- PROB_2: incompatible type error
}
}
}
案例1:
问题1:返回类型为T extends TestIfc
,但返回了TestImpl implements TestIf
,出了什么问题?
问题2:与问题1类似,如何在不进行外部强制转换的情况下进行纠正? 请帮忙。
案例2:
public interface SuperIfc<T> {
public T create(Object label);
}
class Type {
public static Type of(){
return new Type();
}
}
------
public class SubClass<Type> implements SuperIfc<Type>{
@Override
public Type create() {
return Type.of(); <---- PROB_1: cannot resolve method
}
}
-------
public class SubClass<T extends Type> implements SuperIfc<Type>{
@Override
public Type create() {
return Type.of(); <---- PROB_1: is resolved
}
}
SuperIfc<Type> object = new SubClass(); <-- PROB_2 Unchecked assignement warning
SuperIfc<Type> object = new SubClass<TypeImpl>(); <-- PROB_3: bound should extend Type
I would like to know how to resolve Case_2, PROB_1 and PROB_2 together?
How to write subclass for generic super class with class types and what are the rules?
What should be taken care when changing generic
T
to classType
while subclassing? may be the difference between below and when to use?public class SubClass<Type> implements SuperIfc<Type> public class SubClass<Type> implements SuperIfc public class SubClass implements SuperIfc<Type> public class SubClass<T extends Type> implements SuperIfc<Type> public class SubClass<T extends Type> implements SuperIfc<T> public class SubClass<T> implements SuperIfc<Type>
SuperIfc<TypeImpl> object = new SubClass<>();
否则你就在使用原始类型。 - mattpublic static TestIfc of(int choice)
- matt