-2
interface TestA {
    String toString();
}

public class Test {
    public static void main(String args[]) {
        System.out.println(new TestA() {
            public String toString() {
                return "test";
            }
        });
    }
}

This will print test as output.

  1. Can anyone explain how this works?
  2. When I change the method name toString() as printString, it will print only a memory address.Explain how it works.
Kartik
  • 7,677
  • 4
  • 28
  • 50
Mash962
  • 59
  • 1
  • 7
  • 3
    `TestA` is an object, which has override the `toString` method (from `Object`), which is used by `PrintStream` (`PrintStream` calls the object's `toString` method). The default implementation of `toString` prints the objects `hashcode` – MadProgrammer Nov 14 '18 at 04:33

3 Answers3

3

The code:

new TestA() {
    public String toString() {
        return "test";
    }
}

is an anonymous class, which can be thought of as a sort of on-the-fly class definition and instantiation. This class definition implements a toString() method, which happens to return the string test. This anonymous class, when passed to System.out.println, then would result in test being printed.

If you change TestA#toString to TestA#printString, then there is no longer an implementation of toString, and the default behavior of Java is to print the hashcode.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
2

The Object class defines a method toString() that returns a "String representation" of the object. The base method returns the class name and hash code.

It's generally a good idea to override the toString() method and return a better representation.

There are many things in Java that will call an object's toString() method. System.out.println() is one of them. Another common one is the + operator when you are concatenating to a String (like "hello " + myObj).

In your first example, you're creating an anonymous inner class instance of the TestA interface, and overriding toString(). That means that System.out.println() prints the "test" String you defined.

If you rename the method, now you just get the default Object implementation of toString(), and get the "memory address" version.

Ben P.
  • 52,661
  • 6
  • 95
  • 123
1

Object is the super class of all the classes in Java and it has a method toString() which prints the object reference.
If you print any object, java compiler internally invokes the toString() method on the object.
Here you are printing new TestA() so it is calling toString method internally, which you have overridden to print test.

But when you change the name of the method then it calls the toString implementation of Object class.

Kartik
  • 7,677
  • 4
  • 28
  • 50
Pooja Aggarwal
  • 1,163
  • 6
  • 14