Wednesday 12 March 2014

Generics : Multiple Bounds

A type parameter can have multiple bounds

Ex:
<T extends C & A & B>

interface A{

}

interface B{

}

class C implements A,B{
 String name;

 C(String name){
  this.name = name;
 }

 public String toString(){
  return name;
 }

 static <T extends C & A & B > void show(T var){
  System.out.println(var);
 }

 public static void main(String args[]){
  C obj1 = new C("Object1");
  show(obj1);
 }
}

Output
Object1

static <T extends C & A & B > void show(T var)
The type variable T must be the Object for all the types C, A and B.

Lets say, Class C only implements interface A like below.

class C implements A{
 String name;

 C(String name){
  this.name = name;
 }

 public String toString(){
  return name;
 }

 static <T extends C & A & B > void show(T var){
  System.out.println(var);
 }

 public static void main(String args[]){
  C obj1 = new C("Object1");
  show(obj1);
 }
}

When you tries to compile above program, compiler throws below error.

C.java:18: error: method show in class C cannot be applied to given types
show(obj1);
^
required: T
found: C
reason: inferred type does not conform to declared bound(s)
inferred: C
bound(s): C,A,B
where T is a type-variable:
T extends C,A,B declared in method <T>show(T)
1 error
Since here obj1 is of type class “C”, which implements interface “A”, but not implements interface “B”. But as you observe the prototype of the method show()

static <T extends C & A & B > void show(T var)

'T var' must be a type of C, A and B. but in this case obj1 is a type of C and A, but not B. So Compiler throws the error.

If one of the bounds is a class, it must be specified first.

class C implements A,B{
 String name;

 C(String name){
  this.name = name;
 }

 public String toString(){
  return name;
 }

 static <T extends A & C & B> void show(T var){
 }

 public static void main(String args[]){
  C obj1 = new C("Object1");
  show(obj1);
 }
}
    
As you observe C is the class which implementing the interface A and B.

So the order of method should be
static <T extends C & A & B> void show(T var)

class name must comes first in multiple bounds. When trying to compile the above program compiler throws the below error.

C.java:12: error: interface expected here
static <T extends A & C & B> void show(T var){
^
1 error


Prevoius                                                 Next                                                 Home

No comments:

Post a Comment