Forums Register Login

Problem with output

+Pie Number of slices to send: Send
I am new to java . Can anyone please help me in doing this.The below program is printing Object on console . but I can't understand why it is returning that.Please help...............

public class Main{
public static void print(Object obj){
System.out.println("Object");
}
public static void print(String str){
System.out.println("String");
}
public static void main(String[] args) {
Object s=new String("Hello World");
print(s);
}
}
+Pie Number of slices to send: Send
Hi,

Welcome to JavaRanch!

Your two print() methods are called "overloaded" methods: methods with the same name, but different arguments. It's up to the Java compiler to choose which of a set of overloaded methods should get called. When making this decision, the only thing the compiler looks at is the declared types of the arguments you're passing to the method: in this case, is "Object" because s is declared to be of type "Object". The fact that s really points to a String doesn't matter at all.

Overloaded methods are different that "overridden" or polymorphic methods. These are methods in different classes (i.e., multiple subclasses and a superclass) which have the same name and the same argument types. For those methods, the decision of which method to call is deferred until runtime; then the actual type of the object the method is called on does actually matter.
Don't mess with me you fool! I'm cooking with gas! Here, read this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 816 times.
Similar Threads
Polymorphism and casting
Iam Getting runtime Error...(What is Down Casting)
Overloading pb
hashcode()...
strings??
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 17:03:47.