| Author |
why new date() prints date ?????
|
mano ranjan
Ranch Hand
Joined: Jul 12, 2007
Posts: 102
|
|
Hi, In java new Date() prints the current date with time. but when i try to print any of class object it prints the memory location i.e(new Test() prints test@2e3ee...). So why is so, because both are objects why only date object prints date not the memory location..... thanks mano
|
 |
Dan Murphy
Ranch Hand
Joined: Mar 29, 2005
Posts: 126
|
|
Because the Date() class overrides Object.toString(). If a class doesn't override this method, the implementation defined on Object is called, which just prints an object's class name and memory location. [ March 16, 2008: Message edited by: Dan Murphy ]
|
SCJP, SCJD, SCWCD
|
 |
Ernest Friedman-Hill
author and iconoclast
Marshal
Joined: Jul 08, 2003
Posts: 24051
|
|
|
When you print an object, println() calls String.valueOf(theObject), which calls theObject.toString() if "theObject" is not null. Therefore, if a class overrides the toString() method to return something interesting, that's what you see when you print the object. The "memory address" (actually not, but that's another story) is what java.lang.Object.toString() returns, so it's what you get by default for a class that doesn't override this method.
|
[Jess in Action][AskingGoodQuestions]
|
 |
mano ranjan
Ranch Hand
Joined: Jul 12, 2007
Posts: 102
|
|
Hi, thanks for your reply... one more question in java.. what is the difference between tostring() method which is present in object class and toString() method in String class... i.e(Object.tostring() and String.toString()).. why java has two tostring() methods implemented in java.. why cant any one be used??? thanks mano
|
 |
Prahlad Joshi
Ranch Hand
Joined: Apr 21, 2007
Posts: 44
|
|
|
String toString() is overriding Object toString() method.
|
 |
mano ranjan
Ranch Hand
Joined: Jul 12, 2007
Posts: 102
|
|
Hi, thanks for your reply, So what is the main difference between these two methods . in what situation they are used for??? thanks mano.
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19216
|
|
toString is used to display information on an object. Now for Object there is no data to show, so Sun has decided the method should show the class name and the hexidecimal hash code. For String however, there is something to show - the contents of the String. Therefore, toString returns the String itself. Similarly, for most Collection classes, toString returns a String starting with [ followed by all elements separated by a , and ending with a ]. If you create a new class, it inherits toString from its super class. If you have extra data to show you can choose to override toString to display the data you feel is more appropriate. For a Person class, that could be the name.
|
SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
|
 |
 |
|
|
subject: why new date() prints date ?????
|
|
|