This question already has answers here:
JAVA Object/String method overload [duplicate]
(7 answers)
Closed 8 years ago.
This question is bothering me for a while.Please help
Suppose there are two methods
public void add(Object obj){
/* some logic*/
}
public void add(String str){
/*Some logic*/
}
so when i call add(null) which method will get executed and why?
thanks
In this case the String argument version wins, because String is a more specific type as every class is a subclass of Object (except itself).
Anyway, you'll still be able to call the Object argument version by casting.
e.g.
app.add((Object) null);
If there're more than one potential match, such as having a version of add(Integer i) version available, it's an error, and won't compile.
It will call method with String argument...
classes in Java are direct or indirect subclasses of Object. So String is a subtype of Object, the method overloaded to accept a String is more specific than the method overloaded to accept an Object. A String can be converted (upcast) to Object, but an Object cannot be converted (downcast or upcast) to String, so the method taking the String argument is more specific. Therefore, print(String s) will be invoked by the call print(null).
Related
This question already has answers here:
What is the meaning of "this" in Java?
(22 answers)
Closed 2 years ago.
I'm a beginner to coding and I recently learned about this and toString(). I'm not exactly sure what this is and what it does. Can someone explain it in simple words?? Also, when do I have to use it and when do I not?
One more question, why don't we have to use this in the toString() method if we already used it in a constructor?
Thank you so much
This is to refer to the current object. This is in contrast to "super" which refers to the current objects parent.
Usually "this" is used to distinguish instance variables from parameters. For example:
public class Person {
private String name;
public Person(String name) {
this.name = name;
}
}
If you want to represent any object as a string, toString() method comes into existence.
The toString() method returns the string representation of the object. So you can print and see the value.
If you print any object, java compiler internally invokes the toString() method on the object. So overriding the toString() method, returns the desired output, it can be the state of an object etc. depends on your implementation.
https://www.javatpoint.com/understanding-toString()-method
this is used to call Current Object/Current method and toString is used to convert any datatype into String. Like int into String. This is a keyword in java and toString is a predefined method.
This question already has answers here:
What issues should be considered when overriding equals and hashCode in Java?
(11 answers)
java why should equals method input parameter be Object
(6 answers)
Closed 5 years ago.
I'm doing a course in Java and very frequently when equals method is defined in new classes its argument is Object rather than the actual type of the class. Code example:
public class TestClass {
String label, value;
public TestClass(String label, String value) {
this.label = label;
this.value = value;
}
public boolean equals(Object o) {
TestClass t = (TestClass) o;
return this.value.equalsIgnoreCase(t.value);
}
}
Why is this a good practice? Maybe if I want to use polymorphism later this would be helpful. Is it a good practice to use Object as argument even if I don't think currently that I'll need polymorphism but I should still account for it just in case?
Also what bothers me is that we never check whether the object will actually be of type TestClass. Why should we have an instanceof check?
You should do the type check yourself, just casting is not safe as you said, as it can be the wrong type, and then it will throw an ClassCastException.
The reason for using object is that you may have different classes which could be equal (although this is rare), if you don't override the object form of equals then you will face issues when you use collections, as things won't be equal that should be, as the collections will use the object form.
Theoretically there could be a generic equals interface, but the equals method predates genetics, and also being able to check any object with any other simplifies a lot of code.
This question already has answers here:
How is an overloaded method chosen when a parameter is the literal null value?
(8 answers)
Closed 8 years ago.
I tried the following code, but don't understand the output:
Class A{
public void print(Object o){
System.out.println("Object");
}
public void print(String o){
System.out.println("String");
}
public static void main(String arr[]){
A obj = new A();
obj.print(null);
}
}
Output: String
Why??
Thanks for your attention!
The method with the more specific argument type is chosen. String is more specific than Object.
Note that if you had another print method with, say, an Integer parameter, you would get a compilation error, since in that case the compiler would have no rule to decide whether to call print(String) or print(Integer). The reason it works when you have print(String) and print(Object) is that String is a sub-class of Object, and therefore print(String) is preferred.
If there's method overloading, the compiler search for the method from the most specific type to least specific type
From JLS specification
15.12.2.5. Choosing the Most Specific Method
So String is a more specific type compared to the Object.
The least generic method among the matching methods will be selected by the compiler.
i.e, the compiler will first find out that both String and Object can be null. Then it selects the one which is at a lower level in the class hierarchy. (Object is at a higher level than String)
This question already has answers here:
Which overload will get selected for null in Java?
(3 answers)
Strange Java null behavior in Method Overloading [duplicate]
(4 answers)
Closed 9 years ago.
In the following program:
public class PolyEx1 {
public static void main(String[] args) {
A refA = new A();
refA.method1(null);
}
}
class A {
public void method1(Object o) {
System.out.println("o");
}
public void method1(String str) {
System.out.println("str");
}
}
The output is "str", can someone explain me why str was printed? I am not able to understand this.
As explained by Rohit here,
That is because String class extends from Object and hence is more
specific to Object. So, compiler decides to invoke that method.
Remember, Compiler always chooses the most specific method to invoke.
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.
However, if you have two methods with parameter - String, and Integer,
then you would get ambiguity error for null, as compiler cannot decide
which one is more specific, as they are non-covariant types.
As described in Section 15.12.5 of JLS
Java try to use the most specific applicable version of a method.
String extends Object and so the method using String as parameter is always called.
If you try to add a method that take an Integer input it will throws error as ambiguous methods, because String and Integer both of them are more specific than Object but none is more specific than the other one
public void method1(String str) will get executed because object is string supperclass so the string method will be called.
This question already has answers here:
Method overloading and choosing the most specific type
(9 answers)
Why this behavior in overloading [duplicate]
(3 answers)
Closed 9 years ago.
Just out of curiosity I tried this example.
public class Class1 {
public void method(Object obj){
System.out.println("Object");
}
public void method(String str){
System.out.println("String");
}
public static void main(String... arg){
new Class1().method(null);
}
}
The output being "String". I want to know on what basis the JVM decides to invoke method taking String as argument and not Object.
Whenever more than one overloaded methods can be applied to the argument list, the most specific method is used.
In this case either of the methods can be called when passing null, since the "null type" is assignable to both Object and to String. The method that takes String is more specific so it will be picked.
Whenever there's Method Overloading, the JVM will search for the method from the most specific type to least specific type
See the JLS specification
15.12.2.5. Choosing the Most Specific Method
It is one of the puzzle of Java Puzzlers by Joshua Bloch - Puzzle 46: Case of the Confusing Constructor
Java Compiler chooses the most specific method.
String is a more specific type compared to the Object.
Becaue you are passing null in calling method and you defined void method(String str)
And String always initlize with null. it will find that matching parametrized method.
Thats y u got "str" on console.
When you are doing method overloading, jvm tries to the next in hierarchy. For e.g. if you overload methods with long and int, but invoke method by passing byte, it will first go to int as it is next in hierarchy to byte.
It's because of method Overloading
The most specific method is chosen at compile time.
As 'java.lang.String' is a more specific type than 'java.lang.Object'. In your case it returns String.