Friday 18 June 2010

What happens when object is passed to System.out.println()

When any object is passed to  System.out.println(),  by default it calls to the toString() of
Object class. If  class overrides it then overrided toString method would be called.

Example:
Before Overriding toString method:
public class MyClass
{
public static void main(String args[])
{
MyClass myclass=new MyClass();
System.out.println(myclass);
}
}
O/P- hexadecimal number.
Reason: toString method is not overrided in MyClass. Object toString is getting called.

After Overriding toString method:
 
public class MyClass
{
public String toString()
{
return "hello";
}
public static void main(String args[])
{
MyClass myclass=new MyClass();
System.out.println(myclass);
}
}
O/P:
hello

No comments:

Post a Comment