Marin
Marin

Reputation: 12920

Override of toString() that makes use of the overridden toString()

Basically this is what I am trying to achieve.

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

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

Problem, toString() gets called recursively.

I can't call super.toString() because that's not what I want. I want 'this' to call the original toString().

This

this.super.toString() 

doesn't work for obvious reasons.

I'm running out of steam, can this be done once a method gets overridden? I.e. call the original implementation ?

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

This is not a project , or work. Just playing(learning) with Java language. Thanks

Upvotes: 6

Views: 18253

Answers (2)

Sergey Orshanskiy
Sergey Orshanskiy

Reputation: 7054

Actually, I was trying to achieve the same thing, where super.toString() wasn't exactly what I wanted. I believe that this is not possible.

Specifically, I have a domain class in Groovy/Grails, and I wanted to override its toString() method to add some extra 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 e.g.

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

In the other:

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

Upvotes: 0

SLaks
SLaks

Reputation: 888293

You're looking for super.toString().

Upvotes: 10

Related Questions