• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Passing null as a method argument

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi, I have a doubt when i pass null as an argument to an overloaded method as in the following code

public void method1(Object o){
System.out.print("Inside Object");}

public void method1(String s){
System.out.print("Inside String");}

static void main (String[]args){
method1(null);}

When this is executed inside string gets printed.


Now if i change the code as follows

public void method1(StringBuffer o){
System.out.print("Inside Object");}

public void method1(String s){
System.out.print("Inside String");}

static void main (String[]args){
method1(null);}

now i get a compile time error complaining of ambuiguity.

is it that if a superclass type is present then the code compiles
 
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Karthik,
You are right...In the first case when null is passed..the compiler calls the most specific of the two...it calls the method which takes String object argument.In the second case there is no inheritance relationship between String and StringBuffer....the compiler can't decide abt the method call...hence the compile time error.
 
reply
    Bookmark Topic Watch Topic
  • New Topic