0

I am new to Java and want to ask this question: Why don't I have to use anonymous class' overrode method, but instead just use it's object to reach the overrode method?

I hope I made myself clear, but if not, I'd like to refer to the image below:

enter image description here

This is my anonymous class, it's inside a method called instanceMethod();

Here, I test this with my ClassTester.java class

enter image description here

My question is that even though I use System.out.println(demo);, I still get the same result, i.e.,

enter image description here

So this means that I don't need to use System.out.println(demo.toString());

Do you know the reasoning behind this? Does it work like a constructor?

Any help is appreciated.

Best.

Burakhan Aksoy
  • 319
  • 3
  • 14
  • Not sure exactly what you mean, but `System.out.println(demo)` is overloaded for various argument types, and if you just give it an `Object` it internally calls `toString` on that object (after a null-check). – Thilo Mar 07 '21 at 07:29
  • Just look at the code - `println` simply calls `toString`. Has nothing to do with inheritance really. If you think about it - how else would `println` - or anything else - turn something into a `String`? This is the exact reason `Object` has an overridable `toString` method. – Boris the Spider Mar 07 '21 at 07:29
  • Related: https://stackoverflow.com/q/17051481/6367213 – Janez Kuhar Mar 07 '21 at 07:33

0 Answers0