Saturday 8 February 2014

Overloading varargs

 Just like normal methods, java provides facility to overload vararg methods also.

Example
class VaragOverload{

 void print(int ... a){ 
  for(int i=0; i < a.length; i++){
   System.out.println(a[i]);
  }
 }

 void print(boolean ... a){
  for(int i=0; i < a.length; i++){
   System.out.println(a[i]);
  }
 }

 public static void main(String args[]){
  VaragOverload obj = new VaragOverload();
  obj.print(1,2,3);
  obj.print(true, false, true);
 }
}

Output    
1
2
3
true
false
true 
      
Ambiguity while using varargs
Consider the above example, there is a problem in that. Try to call the method “print” with no arguments, then compiler throws the error, since it can't differentiate which overloaded method, it should call.

Example      
class VaragOverload{
 void print(int ... a){
  for(int i=0; i < a.length; i++){
   System.out.println(a[i]);
  }
 }
  
 void print(boolean ... a){
  for(int i=0; i < a.length; i++){
   System.out.println(a[i]);
  }
 }
  
 public static void main(String args[]){
  VaragOverload obj = new VaragOverload();
      
  obj.print(1,2,3);
  obj.print(true, false, true);
  obj.print();
 }       
}
      
When you try to compile, compiler throws the below error
VaragOverload.java:20: error: reference to print is ambiguous, both method print(int...) 
in VaragOverload and method print(boolean...) in VaragOverload match     
    obj.print();
       ^
    1 error  



Overloading Methods                                                 Constructors                                                 Home

No comments:

Post a Comment