Override toString () that uses overridden toString ()

This is basically what I'm trying to achieve.

classname @address (?) [original toString() ], object name, object age

 @Override public String toString() { return String.format("%s , %s , %d", this.toString(), this.getName(),this.getAge()); } 

The problem is, toString() is called recursively.

I cannot call super.toString() because this is not what I want. I want this call the original toString() .

it

 this.super.toString() 

not working for obvious reasons.

It’s running out for me, can this be done when the method is overridden? That is, to call the initial implementation?

(my edit) Basically I need to: override toString to display the two properties of the 'this' object, and I also want 'this' to call the original toString.

This is not a project or a job. Just a game (training) with the Java language. thanks

+6
source share
2 answers

You are looking for super.toString() .

+10
source

Actually, I tried to achieve the same thing where super.toString() was not quite what I wanted. I believe this is not possible.

In particular, I have a domain class in Groovy / Grails, and I would like to override its toString() method to add additional information:

 class Child extends Parent { public String toString() { return super.toString(this) + extra_info // not possible!!! } } 

This is not identical to return super.toString() + extra_info . In one case, I get, for example,

com.example.domain.Parent : 15, extra_info . (False. The instance is the same, but toString contains type information.)

In a different:

com.example.domain.Child : 15, extra_info . (Right, but not possible.)

0
source

Source: https://habr.com/ru/post/903636/


All Articles