You need to use super
to reference your parent class.
class A {
@Override
public String toString() {
return "A's toString()";
}
}
class B extends A {
@Override
public String toString() {
return super.toString() + " " + "B's toString()";
}
}
B b = new B();
System.out.println(b); // prints "A's toString() B's toString()"
Edit:
If your child's toString()
always calls the parent's, then you don't even need the toString()
in the child.
If you want to keep a custom toString()
for your child that is different than the parent's in some case, but you also want to be able to call the parent's toString()
from the child, make a delegation method.
class B extends A {
@Override
public String toString() {
...
}
public String parentsToString() {
return super.toString();
}
}
B b = new B();
b.parentsToString(); // will return the output of A's toString()