Problem with the same method name in parent as extended class

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

How can I access the toString() method of the parent class from a test application?

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

Thanks in advance for your help.

+4
source share
3 answers

You can not. This is called polymorphism and that OOP is all. A subclass of toString overrides (overrides) the parent toString method.

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

 @Override public String toString() { // redefine the toString method } public String parentToString() { return super.toString(); } 
+11
source

It should be called as

 class Child extends Parent{ public String toString() { String superToString = super.toString(); // do something with superToString return someString; } } 

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

+5
source

with the super keyword, you can access the method of the parent class.

0
source

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


All Articles