5.4 super Keyword
From CS Awesome 2CC BY-NC-SA 4.0Original page
Java1 class period2 exercises6 graded tests
Files
5.4 super Keyword
Each coding exercise has its own folder. Open its .java file and press Run to try it. Run Tests checks every graded exercise in this lesson at once.
Sometimes you want the subclass to do more than what a superclass’ method is doing. You want to still execute the superclass method, but you also want to override the method to do something else. But, since you have overridden the parent method how can you still call it? You can use super.method() to force the parent’s method to be called.
We’ve used super() before to call the superclass’ constructor. There are two uses of the keyword super:
- super(); or super(arguments); calls just the super constructor if put in as the first line of a subclass constructor.
- super.method(); calls a superclass’ method (not constructors).
The keyword super is very useful in allowing us to first execute the superclass method and then add on to it in the subclass.
In the example below, the Student class overrides the getFood method of the Person class, and it uses super.getFood() to call the Person getFood method before adding on to it. Here, a Person is associated with the food “Hamburger” and a Student is associated with “Hamburger” and “Taco”.
How does this work? Remember that an object always keeps a reference to the class that created it and always looks for a method during execution starting in the class that created it. If it finds the method in the class that created it, it will execute that method. If it doesn’t find it in the class that created it, it will look at the parent of that class. It will keep looking up the ancestor chain until it finds the method, all the way up to the Object class. The method has to be there, or else the code would not have compiled.
When the student getFood() method is executed it will start executing the getFood method in Student. When it gets to super.getFood() it will execute the getFood method in Person. This method will return the string "Hamburger". Then execution will continue in the getFood method of Student and return the string "Hamburger and Taco".
You can step through this example using the Java Visualizer by clicking on the following link: Super Example.
The toString method is commonly overridden. A subclass can override toString but in its new toString method, it can call super.toString() to get a string to which it can add its own instance variables.
// overridden toString() in subclass
public String toString()
{
return super.toString() + "\n" + subclassInstanceVariables;
}
Exercise 1
Add another subclass called Vegan that inherits from the Student class. Add a Vegan contructor that takes a name as an argument and passes it to the super constructor. Override the getFood() method in Vegan to call the superclass getFood() but add a “No ” in front of it and then say “but ” and add a vegan food. Change Javier to a Vegan object in main() and try it out!
Open the
01-SuperExfolder and editPerson.java. Press Run to try it; Run Tests checks it (2 tests).
Check your understanding: Given the following class declarations, and assuming that the following declaration appears in a client program:
Base b = new Derived();, what is the result of the callb.methodOne();?public class Base { public void methodOne() { System.out.print("A"); methodTwo(); } public void methodTwo() { System.out.print("B"); } } public class Derived extends Base { public void methodOne() { super.methodOne(); System.out.print("C"); } public void methodTwo() { super.methodTwo(); System.out.print("D"); } }Answer it on CS Awesome: https://runestone.academy/ns/books/published/csawesome2/topic-5-4-super.html#qoo_6s
Coding Challenge: Customer Info
The Customer class below keeps track of the names and addresses of customers. It has a toString method that prints out the name and address of the object.
- Create a subclass
OnlineCustomerthat inherits from theCustomerclass and adds a new instance variable for the email address of a online customer. - Write an OnlineCustomer constructor that take 3 arguments, name, address, email, and passes the name and address to the super (Customer) constructor.
- Override the
toStringmethod in theOnlineCustomerclass to call the super class’stoStringmethod and then add on the email address. See the example above for help. - Test the class by uncommenting the
OnlineCustomerobjects in the main method.
Exercise 2
Complete the OnlineCustomer class to inherit from Customer and add an email address, a constructor, and override the toString() method.
Open the
02-challenge-9-4-Customer-superfolder and editCustomer.java. Press Run to try it; Run Tests checks it (4 tests).
Summary
- The keyword super can be used to call a superclass’s constructors and methods.
- The superclass method can be called in a subclass by using the keyword super with the method name and passing appropriate parameters.
For teachers
5.4 super Keyword
Students read CSAwesome2's “super Keyword” in CS Room and work through its 2 Java coding exercises.
- Time: 1 class period
- Tests: 6 in 2 graded exercises, set up for you when you import the lesson
Goals
- The keyword super can be used to call a superclass’s constructors and methods.
- The superclass method can be called in a subclass by using the keyword super with the method name and passing appropriate parameters.
Before class
- Import the lesson into your class from the Lessons page, or with New assignment → Use a lesson. It arrives as a draft with its tests already set up.
- Publish it.
- The original page, with its multiple-choice questions, is on CS Awesome: https://runestone.academy/ns/books/published/csawesome2/topic-5-4-super.html
- CS Awesome's own teacher materials: the CS Awesome teacher site
In class
- Students read
README.md. Questions that need CS Awesome's interactive widgets link back to it. - Students do exercises 01–02, each in its own folder, pressing Run to try their code.
- Run Tests checks every graded exercise at once; scores appear in the Gradebook. Grading uses your copy of the tests, so a student who edits theirs does not change the grade.
Exercises
| Folder | File | Grading | Tests |
|---|---|---|---|
01-SuperEx | Person.java | Autograded | 2 |
02-challenge-9-4-Customer-super | Customer.java | Autograded | 4 |
Teachers can download a reference solution after signing in.