• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Overloaded functions?

 
Kedar Dravid
Ranch Hand
Posts: 333
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Consider the following:

1. public class MethodOver {
2. private int x, y;
3. private float z;
4. public void setVar(int a, int b, float c){
5. x = a;
6. y = b;
7. z = c;
8. }
9. }

Which two overload the setVar method? (Choose Two)

A. void setVar (int a, int b, float c){
x = a;
310 - 035
y = b;
z = c;
}
B. public void setVar(int a, float c, int b) {
setVar(a, b, c);
}
C. public void setVar(int a, float c, int b) {
this(a, b, c);
}
D. public void setVar(int a, float b){
x = a;
z = b;
}
E. public void setVar(int ax, int by, float cz) {
x = ax;
y = by;
z = cz;
}

Answer: B, D.
My question: Why not C?
 
David Ulicny
Ranch Hand
Posts: 724
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Java Language Specification:
If two methods of a class (whether both declared in the same class, or both inherited by a class, or one declared and one inherited) have the same name but different signatures, then the method name is said to be overloaded.

C will produce compile time error.
[ February 10, 2005: Message edited by: David Ulicny ]
 
Animesh Shrivastava
Ranch Hand
Posts: 298
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In C, u have
public void setVar(int a, float c, int b) {
this(a, b, c);
}

If u see inside the method body u have "this(a,b,c)",
"this " keyword can only be used in a constructor, it cannot be used inside any method, so that would display a compilation error. Thats why i guess its opted out as the right choice
 
Kedar Dravid
Ranch Hand
Posts: 333
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
But the signatures of options B,C are the same.
So, if B is one of the correct answers, why is not C also correct?
 
David Ulicny
Ranch Hand
Posts: 724
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because if can't to compile it you can't talk about overloading
 
Kedar Dravid
Ranch Hand
Posts: 333
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Animesh and David, I've got it!
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic