This question already has answers here:
Which overload will get selected for null in Java?
(3 answers)
Closed 8 years ago.
I want to know whether this is a valid overloading :
public class OverLoadingTest{
private void callFunction(Object object){
System.out.println("Printing Object");
}
private void callFunction(String string){
System.out.println("Printing String");
}
}
Further more, since someone asked me this question.
If I do like this,
OverLoadingTest test = new OverLoadingTest();
test.callFunction(null);
what will be printed ?
Of course my opinion is that it isn't valid overloading at all.
So no question of the second part.
Please tell me about this with some explanation.
The method with the least generic argument is called. So, in your case, it will be method accepting String
Note : If 2 classes are at the same level, then you will get an ambiguous call exception. For example if one method took String and another took Exception.
If more than one member method is both accessible and applicable to a method
invocation, it is necessary to choose one to provide the descriptor for
the run-time method dispatch.
The Java programming language uses the rule that the most specific method is chosen.
See more details in JSL 15.12.2.5
In your case, String method will be invoked, if argument is String or null and for other argument's types Object method will be invoked.
In your example, if you define one more method with argument type that is not String (e.g Integer), can't compile the source as it is ambiguous to be invoked between the methods with String and Integer as they are same level.
Related
This question already has answers here:
Methods vs Constructors in Java
(11 answers)
Closed 2 years ago.
actually i'm beginner my questions might be silly And my doubt is what was actual purpose of methods vs constructors in java,
we can pass values in both methods & constructor parameters,
which one is recommended and why??
A Java method is use to perform some action which is also know as Function. Where you can pass parameter. They must have return type.
A Constructor is special method use to initialise the object . Constructor must not have return type. Constuctor name must be same as class name.
Constructor is used to initialize an object whereas method is used to exhibits functionality of an object.
Constructors are invoked implicitly whereas methods are invoked explicitly.
Constructor does not return any value where the method may/may not return a value.
In case constructor is not present, a default constructor is provided by java compiler. In the case of a method, no default method is provided.
Constructor should be of the same name as that of class. Method name should not be of the same name as that of class.
This question already has answers here:
Definition of a method signature?
(7 answers)
Closed 7 years ago.
I read a book titled 'Object First with Java' and in page 7 the author mentioned that the method signature "provides information needed to invoke that method". And the the author gave the following example:
void moveHorizontal(int distance)
However, today when I was watching a video about C# on Pluralsight, the author said that "the return type of a method is not part of the method signature".
I'm confused now and would like know what is a method signature?
A method-signature is the part of the method based on which you overload / override it. It contains :
The method name.
The arguments passed to it.
It doesn't contain :
Scope / access modifier
return type.
Method signature is used in interfaces and in abstract classes, but we always define the method data type(return type). It will be something invaluable if the return type is not a part of the signature.
This question already has answers here:
Overloaded method selection based on the parameter's real type
(7 answers)
Closed 9 years ago.
I have two methods in a class...
public void method(String var1, String var2, Object var3) {
//do stuff
}
public void method(String var1, String var2, Object[] var3) {
//do stuff
}
When I make the following call... obj.method("string", "string", obj) the correct method is called, however, when I try to call obj.method("string", "string", obj[]) the first incarnation of that method is called.
Is there any annotation or "hint" I can give to make sure the method I anticipate being called will be called? I know an Object[] is anObject, but I would hope that at runtime the method with Object[] would be called before Object.
Nope, for me this calls the second method as expected!
In the case where you want one to be called over the other, then the hint you'd give is usually a cast to the exact parameter type expected by the method (this cast will work even on null.) So using (Object)arr would force the first method to be called, but by default it will definitely call the second method (on all correct versions of the JVM anyway - contrary to popular belief, this scenario is covered explicitly in the JLS and thus is not ambiguous.)
In Java the method overload happens during compile time. That means which method is called was decided during program compilation. Note this is different from method overriding.
This question already has answers here:
Strange Java null behavior in Method Overloading [duplicate]
(4 answers)
Behavior of method overloading in java [duplicate]
(1 answer)
Closed 9 years ago.
I have the following code
public class HelloWorld {
public void printData (Test t) {
System.out.println("Reached 1");
}
public void printData(NewTest t) {
System.out.println("Reached 2");
}
public static void main(String args[]) {
HelloWorld h = new HelloWorld();
h.printData(null);
}
}
and I have two simple classes
class Test {
}
class NewTest extends Test {
}
and the output I got is Reached 2
Why the second function was selected for executing and not the 1st one? Also when I tried the same code by making another class NewTest2 extending Test and analogous printData() function it gave me compile time error. Is there any rule to select which function must be executed and when?
Why the second function was selected for executing and not the 1st one?
Because the method taking NewTest is more specific than the method taking Test, and both are accessible and applicable.
However, when you've got two subclasses of Test, neither conversion is more specific than the other, hence the call is ambiguous.
See JLS section 15.12.2.5 for the exact rules involved:
If more than one member method is both accessible and applicable to a method invocation, it is necessary to choose one to provide the descriptor for the run-time method dispatch. The Java programming language uses the rule that the most specific method is chosen.
The informal intuition is that one method is more specific than another if any invocation handled by the first method could be passed on to the other one without a compile-time type error.
What IDE do you use ?
In Eclipse "h.printData(null)" is marked red with this error:
The method printData(Test) is ambiguous for the type HelloWorld.
In this case you need to cast null like that:
"h.printData((Test)null)"
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Method Overloading for NULL parameter
In the code below the output is
String
and if I remove the method with the parameter of type String then the output is
Object
I know how overloading of methods acts when the parameter types don't match exactly but I can not understand how null can be treated as an Object and/or a String parameter.
What is the explanation for this?
class C {
static void m1(Object x) {
System.out.print("Object");
}
static void m1(String x) {
System.out.print("String");
}
public static void main(String[] args) {
m1(null);
}
}
It always uses the most specific method according to the Java specs, section 15.12.2.5.
The intro is reasonably specific about it:
If more than one member method is both accessible and applicable to a method invocation, it is necessary to choose one to provide the descriptor for the run-time method dispatch. The Java programming language uses the rule that the most specific method is chosen.
The informal intuition is that one method is more specific than another if any invocation handled by the first method could be passed on to the other one without a compile-time type error.
Generally speaking, and at least for code readability, it's always best to try to be as explicit as possible. You could cast your null into the type that matches the signature you want to call. But that's definitely a questionable practice. It assumes everyone knows this rule and makes the code more difficult to read.
But it's a good academic question, so I +1 your question.
When multiple overloads match a signature, Java picks the most specific method from among them.
The value of null matches both Object and String, but String is a subclass of Object, so String is picked. If you add another overload with a sibling of String in the class hierarchy, you'd get a compile error.\
// DOES NOT COMPILE
class C {
static void m1(Object x) {
System.out.print("Object");
}
static void m1(String x) {
System.out.print("String");
}
static void m1(Integer x) {
System.out.print("Integer");
}
public static void main(String[] args) {
m1(null);
}
}
Here is a link to a post that discusses your code example at some length.
If you need to force the call of a aprticular overloaded method when passing null as parameter, you have to cast it, like this:
m1((String)null);
By doing this, you make sure you're calling the correct overloaded version of the method.
You have to set the type of null to tell Java what function you want to call.
So you do: m1((Object) null); to call the implementation with the Object parameter and you do m1((String) null); to call the other one.
1. As String is also an object the JVM got confused to call which method at runtime.
2. If you want to specify which method to call at runtime, you can do this by explicit casting
eg:
m1((String)null);