-7

I am curious as to why new Java.util.Date() returns Date object but not address(reference) to itself on heap:

System.out.println(new Date()); //Should print address(reference)

of object on heap?

like every other class I've been learning about for example:

Cat cat = new Cat();  //new Cat() returns reference which is stored in cat;

how can I implement it in my classes?

trincot
  • 317,000
  • 35
  • 244
  • 286
new User
  • 53
  • 6
  • 4
    Override `toString()` – Eran Dec 04 '17 at 07:56
  • 4
    Why do you think `new Date()` does not return a reference to a `Date` object on the heap? – Jim Garrison Dec 04 '17 at 07:56
  • 1
    Also note that the [default `toString` inherited from `Object`](https://docs.oracle.com/javase/9/docs/api/java/lang/Object.html#toString--) does **not** print out the address of the object in the heap. It prints out the object's hash code, which isn't its address. – T.J. Crowder Dec 04 '17 at 08:01
  • I always thought of reference as some form of address like 0x23232, Can a date be reference? – new User Dec 04 '17 at 08:14

1 Answers1

3

java.util.Date, like a lot of other classes in the JDK, overrides toString(), which allows you to control the string representation of your objects.

You can, of course, do this for your own classes too.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • 1
    @Override public String toString() { return "meow"; } Works like a charm 10/10 would ask again As to why it works i need to figure it out later :P – new User Dec 04 '17 at 08:07