In the code below:
class A<T extends InterfaceA & InterfaceB>
what does it mean "T should be a type of InterfaceA"?
for example the next code:
class A<T extends Number>
means that T can be an int, a double or any other numeric types. can anyone give me an example to explain the first code?
class A<T extends interfaceA & interfaceB>
means
that T is bounded by two interfaces. Thus,any type argument passed to T must implement interfaceA
and interfaceB
.
Sample program for your understanding :-
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();
}
}
This means that type which argument passed to T must implement interfaces X and Y.
Like shown in the given code :-
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
I hope this much helps you understand and point out the differences!!!