Null value in method parameter [duplicate] - java

This question already has answers here:
Which overload will get selected for null in Java?
(3 answers)
Closed 7 years ago.
I have the following code
import java.util.List;
public class Sample {
public static void main(String[] args) {
test(null);
}
static void test(List<Object> a){
System.out.println("List of Object");
}
static void test(Object a){
System.out.println("Object");
}
}
and I got following output in console
List of Object
Why doesn't this call test(Object a)? Can you some one explain how it took "List as" null?

In a nutshell, the most specific method among the overloads is chosen.
In this case the most specific method is the one that takes List<Object> since it's a subtype of Object.
The exact algorithm Java uses to pick overloaded methods is quite complex. See Java Language Specification section 15.12.2.5 for details.

Always specific first, in cases like that. If you change List to String, it will print the same thing. Every class is child of Object, so if it have to overload, will be to the more specific class.

Related

How do I make a function with overloading? [duplicate]

This question already has answers here:
Why is method overloading and overriding needed in java? [duplicate]
(2 answers)
Closed 4 years ago.
I asked on SE how to make a function that accepts different kinds of variables. People have told me to "overload".
My question: how do I use overloading to make a function that will accept multiple data types (int bool string) as it's input?
Also, what are the advantages and disadvantages of overloading? Is it related to "overloading my computer"?
Overloading is a concept that doesn't hurt your computer but sometimes it makes your head hurt. Not really. Overloading is just writing multiple implementations of a method with the same name but different parameter types. It requires the programmer to write code like this. Notice the return types are the same.
public int SomeMethod(int someValue)
{ //one implementation for ints }
public int SomeMethod(String someValue)
{ //another implementation for strings}
Which method is invoked depends on on the argument type. The method invoked here is the one for integer arguments:
int result = SomeMethod(5);
Another way of doing this is using Generic Methods. This is a little advanced for the question asked, but it might be what you're looking for. The Oracle Java Documentation is a good place to start.
Try looking into generic types: https://docs.oracle.com/javase/tutorial/java/generics/boundedTypeParams.html
Overloading is a concept. It will not affect your computer or your code. It is simply the fact of declaring multiple methods in your class with the same name but different arguments.
For example:
private int doSomething(int anInteger) {
// do something with an integer
}
private int doSomething(float aFloat) {
// do something with a float
}
Doing this will allow you to use the same method name on different parameter types, but have different method implementation.
public void myFunction(String s){ ... }
public void myFunction(int i){ ... }
public void myFunction(bool b){ ... }
Really you should be able to google "java overloading" or something instead of posting on here for this. Googling is a top developer skill. Read the documentation, or your textbook or something.

Checking for valid overloading [duplicate]

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.

null behavior in function overloading with polymorphism [duplicate]

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)"

What is a Type Literal in Java? [duplicate]

This question already has answers here:
Use of TypeLiteral in java
(5 answers)
Closed 9 years ago.
There is an ASTNode subclass called TypeLiteral.
The description of this type of code says that it looks like
( Type | void ) . class
I don't believe I have ever seen anything like this.
Can anyone provide an example of a TypeLiteral, and perhaps additionally of it being used in a Java program?
There is a class called Class that represents the class of an object. It contains various useful methods for introspection on that class and objects of that class. One way to get a class object is to use the Object method getClass(). But if you want to refer to a Class by name of its class, you use a class literal.
Some examples:
class Foo {
void method(Object b) {
if(b.getClass() == Foo.class) {
Foo f = Foo.class.cast(b);
}
Foo.class.getResourceAsStream(...);
Foo.class.getMethod("method", Object.class);
}
}

Overloading method calls with parameter null [duplicate]

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);

Categories