在下面的代码中:
class A<T extends InterfaceA & InterfaceB>
“ T应该是InterfaceA的一种”是什么意思?
例如下面的代码:
class A<T extends Number>
表示T可以是int,double或任何其他数字类型。谁能给我一个例子来解释第一个代码?
class A<T extends interfaceA & interfaceB>
方法
T受两个接口限制。因此,传递给T的任何类型参数都必须实现interfaceA
和interfaceB
。
示例程序供您理解:-
interface X{
public void eat();
}
interface Y{
public void drink();
}
class XYZ implements X,Y{
@Override
public void eat(){
System.out.println("I am eating.");
}
@Override
public void drink(){
System.out.println("I am drinkin too!");
}
}
class A<T extends X & Y> {
public void display(){
XYZ x=new XYZ();
x.eat();
x.drink();
System.out.println("Type of XYZ is "+x.getClass().getName());
}
}
public class Sample1{
public static void main(String[] args) {
A<XYZ> a=new A<>();
a.display();
}
}
这意味着传递给T的参数的类型必须实现接口X和Y。
就像给定的代码所示:-
A<XYZ> a=new A<>(); //here only XYZ(substituted in place of T) can be passed because it implements both interface X and interface Y
我希望这能帮助您理解并指出差异!!!
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句