• Post Reply Bookmark Topic Watch Topic
  • New Topic

What should be the result of running this code?  RSS feed

 
Kiki Tsang
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I got a compilation error (ambiguous at the line square(w)) using eclipse but no error if using javac at command prompt. I wonder what should be the correct answer and why:
public class P082{
public static void main(
String args[]){
new Worker().doOverLoad();
}//end main()
}//end class definition
class Worker{
public void doOverLoad(){
int w = 3;
double x = 4.2;

System.out.println(
new Subclass().square(w) + " " + new Subclass().square(x));
}//end doOverLoad()
}// end class
class Superclass{
public int square(int y){
return y*y;
}//end square()

}//end class Superclass
class Subclass extends Superclass{
public double square(double y){
return y*y;
}//end square()
}//end class Subclass
 
Tobias Hess
Ranch Hand
Posts: 55
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A typeconversion from int to double can safely be done, there's no information loss. Therefore, the call
Subclass.square(w)
is ambiugous, the compiler doesn't know witch one you want: the double, or the int-Version.
 
Kiki Tsang
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, that's what I think too. But when I compile the class using my j2sdk 1.4.2_04, there is no error.
 
chi Lin
Ranch Hand
Posts: 348
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
this is a example of overloading, subClass has two methods
one take int parameter, one take double parameter.
so no conflict.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!