开发者

Issue with same method name in parent as extended class

开发者 https://www.devze.com 2023-02-15 14:57 出处:网络
I have a parent class and extended class, both contain a toString() method. How would I go开发者_StackOverflow社区 about calling the parent class\'s toString() method from the Test app?

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

How would I go开发者_StackOverflow社区 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.


with super keyword you can access parent class method .

0

精彩评论

暂无评论...
验证码 换一张
取 消