Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Problem with output

 
Anil Veer
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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);
}
}
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24208
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic