5

How can I override System.out.println()?

Like I would override toString();

@Override
public String toString() {
    return "x";
}

I want to make it so, that when you call

System.out.println(OBJECT);

It would print the attributes of the object instead of the reference.

Willi Mentzel
  • 27,862
  • 20
  • 113
  • 121
Henri Willman
  • 119
  • 1
  • 5
  • If you override `toString` in the object's class, then it will print whatever you want. – kaya3 Feb 07 '20 at 12:48
  • *Which* attribute of the object? Different objects will have different "attributes". Do you mean you want to print each object's toString() method? – sleepToken Feb 07 '20 at 12:48
  • Also, Overriding the `toString` method and the `System.out.println()` would not give the same result. Those are two different method. – Nicolas Feb 07 '20 at 12:49

2 Answers2

10

Strictly, the answer to your question "How can I override System.out.println()?" is that you can replace System.out with an alternative PrintStream using System.setOut. The PrintStream you supply can implement println however you like (*).

But this is almost certainly not what you mean. You can override the toString() method on your class instead, and then this will be used in all places that want to build a string representation of your instance, not simply System.out.println.


(*) However if you want to conform to the specification, you don't have that much flexibility, e.g. println(Object) "calls String.valueOf(x)".

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
3

Overriding System.out.println IS NOT what you need. In order to do that you would need to extend PrintStream and override all overloaded version of the method printLn. After that you would need to replace the standart stream of your JVM by calling System.setOut().

Every java object has the capability of converting it self to a string representation. In order to "customize" this representation you need to override the toString() method.

printLn will always call toString() independently of the class of your object. That's waht we call polimorphism.

So override to toString() for each class you want a special string representation.

Leonardo Cruz
  • 1,189
  • 9
  • 16