Java - using super to call a method in the parent class
Archive - Originally posted on "The Horse's Mouth" - 2008-01-10 14:23:22 - Graham EllisIf you're writing a Java class in which you override a method from the base class, can you still make use of that base class method in your new code? Yes, you can. You want the super call.
Here's an example - I had a base class called Shape which overrides the toString method. And I was then writing a Rectangle class in which I wanted a further enhanced toString method. So here it is - firstly running toString from Shape and then adding some extra text.
public String toString() {
String firstbit = super.toString();
String result = firstbit + " Rectangle " + width + " by " + height;
return result;
}
The toString method in Java is defined for all Objects as the method which converts the object into a printable string - so that if you ask for an object to be printed this is how it will be formatted. It's a method that all classes that you write will inherit - either from Object or from other classes if you define inheritance yourself, and it is very often overridden at many levels.