简体   繁体   中英

Issue with same method name in parent as extended class

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.

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();
}

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.

使用super关键字,您可以访问父类方法。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM