• 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

over loading

 
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
public class Test {

public void takeMethod(String s) {
System.out.println("A");
}

public void takeMethod(Object s) {
System.out.println(s);
}
public static void main(String[] args){
Test test= new Test();
test.takeMethod(null);
}
}
This is working fine with "A" as out put. Why so, both String and Object can take null.

Then why not
public class asd {


public void takeMethod(Test s) {
System.out.println("A");
}

public void takeMethod(NewOne s) {
System.out.println(s);
}
public static void main(String[] args){
asd test= new asd();
asd.takeMethod(null);
}

}
class Test {
}
class NewOne{}

It is compile error .compiler ambiguity
 
Sheriff
Posts: 22784
131
Eclipse IDE Spring VI Editor Chrome Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The compiler always tries the most specific version. In the first example that's String, and it works because String extends Object.
In the second example, there is no relation between Test and NewOne, so the compiler is at a cross roads and doesn't know which way to go.

Test it, let Test extend NewOne. You'll see it will work.
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic