HomeSearch

Java Super: Parent Class

This Java example uses the super keyword to access a parent class from a descendant class. Super is used with the extends keyword.
Super. 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.ExtendsClass
First example. 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.

And: The Cat scratch method itself calls its parent scratch method from the Animal class. We call a "super" class method.

Java program that uses super 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(); } } Output Animal scratched Cat scratched
Super, Object. 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.
Java program that uses super, 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(); } } Output 366712642
Super, constructor. 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.

Here: The Image class extends the Data class. We invoke the Data constructor from the Image constructor with super().

Java program that uses super constructor 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"); } } Output 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.
A summary. 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.
© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.
Home
Dot Net Perls