5

I have a parent class and extended class, both contain a toString() method.

How would I go about calling the parent class's toString() method from the Test app?

Right now to call the extended class's toString method it's objectname.toString(), but what about the parent class?

Thanks in advance for the help.

Eric
  • 565
  • 1
  • 8
  • 25

3 Answers3

13

You can't. This is called polymorphism, and that's what OOP is all about. The subclass toString redefines (overrides) the parent toString method.

If you want to be able to call the parent one, you need to add another method, with another name:

@Override
public String toString() {
    // redefine the toString method
}

public String parentToString() {
    return super.toString();
}
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • This is exactly what I needed and signed up just to upvote you. Thanks for the help. – Eric Mar 07 '11 at 22:57
5

It should be called like this

class Child extends Parent{

    public String toString()
    {
       String superToString =  super.toString();
       // do something with superToString

       return someString;
    }

}

if you are just going to return super.toString() then there is no need to override toString() in the child class.

Bala R
  • 107,317
  • 23
  • 199
  • 210
0

with super keyword you can access parent class method .

p27
  • 2,217
  • 1
  • 27
  • 55