Home
Map
super: Parent ClassUse the super keyword to access a parent class from a descendant class. Super is used with the extends keyword.
Java
This page was last reviewed on Dec 5, 2022.
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.
extends
class
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.
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
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.
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
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().
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.
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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
No updates found for this page.
Home
Changes
© 2007-2024 Sam Allen.