With this keyword, we can reference the "ancestor" or base class
of a derived class
. Super enables us to access ancestor classes with ease.
Along with the extends keyword, we use super to facilitate object-oriented design. We compose classes from a parent. This sometimes reduces code duplication.
Let us examine a "super" program. First notice the "extends" keyword. Here the class
Cat extends the class
Animal. I call the scratch()
method on Cat.
class
. We call a "super" class
method.class Animal { public void scratch() { System.out.println("Animal scratched"); } } class Cat extends Animal { public void scratch() { // Call super-class method. super.scratch(); System.out.println("Cat scratched"); } } public class Program { public static void main(String[] args) { // Create cat and call method. Cat cat = new Cat(); cat.scratch(); } }Animal scratched Cat scratched
All classes have a parent class
of Object. If a class
has no "extends" class
, it inherits from Object. We can use methods like hashCode()
from Object.
class Page { public void test() { // This class inherits from Object only. // ... So it gains access to methods like hashCode on Object. System.out.println(super.hashCode()); } } public class Program { public static void main(String[] args) { Page page = new Page(); page.test(); } }366712642
With a call to super()
in a derived class
, we can invoke the parent's constructor. We can pass arguments to the super()
method and they are received in that constructor.
class
extends the Data class
. We invoke the Data constructor from the Image constructor with super()
.class Data { public Data() { System.out.println("Data constructor"); } } class Image extends Data { public Image() { // Call the superclass constructor. super(); } } public class Program { public static void main(String[] args) { Image value = new Image(); System.out.println("Done"); } }Data constructor Done
In other languages like C# we use the "base" keyword instead of super. But the meaning is similar. We use these keywords to reference the parent.
Class
composition is not a fix for all design problems. But it can sometimes help complicated programs become simpler. For small projects, though, it is less often needed.