Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

over loading

 
surya goutham datta rejeti
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • 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
 
Rob Spoor
Sheriff
Pie
Posts: 20608
63
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • 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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic