I have the following code :
public class Main {
public void method(Object o)
{
System.out.println("Object Version");
}
public void method(String s)
{
System.out.println("String Version");
}
public static void main(String args[])
{
Main question = new Main();
question.method(null);//1
}
}
why is the result is "String Version" ? and why there is a compiler error if the first method takes a StringBuffer
object ?
Another case : if the first method takes a StringBuffer
object and I write question.method("word");
the result will be "String Version" . Why ? why there is no compiler error ?
The this keyword refers to the current object in a method or constructor. The most common use of the this keyword is to eliminate the confusion between class attributes and parameters with the same name (because a class attribute is shadowed by a method or constructor parameter).
In Java, both this and this() are completely different from each other. this keyword is used to refer to the current object, i.e. through which the method is called. this() is used to call one constructor from the other of the same class.
When we consider a Java program, it can be defined as a collection of objects that communicate via invoking each other's methods. Let us now briefly look into what do class, object, methods, and instance variables mean. Object − Objects have states and behaviors.
When looking at the other case :
package com.snamellit;
public class Main {
public void method(Object o) {
System.out.println("Object Version");
}
public void method(String s) {
System.out.println("String Version");
}
public static void main(String args[]) {
Main question = new Main();
question.method("word");
}
}
If the first method tqkes a StringBuffer and the second a String, there is no confusion possible as "word" is a String and not a StringBuffer.
In Java the identity of a function/method is dependent on 3 things : the name, the type pf the parameters (aka the argument signature) and the classloader. Since both types have a different argument signature the compiler can easily choose the right one and does not raise an error.
The JAVA spec says that in cases like this, the most specific function will be called. Since String is a sub type of Object - the second method will be called. If you change Object to StringBuffer - there is no specific method since StringBuffer is not a sub type of String and vice versa. In this case the compiler does not know which method to call - hence the error.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With