INH - super Keyword (Lesson)
super Keyword
Introduction
Let’s review classes. Take a few minutes to write a Person class. Think about what a person has (instance variables) and what a person does (methods).
Your person class might have instance variables: first name, last name, age, address,…
Now, write a Student class.
Does it have the same instance variables? How about methods?
It would be so easy if we could just reuse the Person class code and maybe just add instance variables like student number or a method for playing sports.
Enter Inheritance!
super Keyword
With inheritance, subclasses can access methods, however, constructors are not inherited. Each class must create their own constructors. However, a subclass can call the constructor from a parent (super) class.
The super keyword is used to access methods or constructors from the superclass.
The superclass method can be called in a subclass by using the keyword super with the method name and passing appropriate parameters.
When using the super keyword, it must be the first statement in the constructor. The superclass constructor can be called from the first line of a subclass constructor by using the keyword super and passing appropriate parameters.
The actual parameters passed in the call to the superclass constructor provide values that the constructor can use to initialize the object’s instance variables. When a subclass’s constructor does not explicitly call a superclass’s constructor using super, Java inserts a call to the superclass’s no-argument constructor.
What does this mean? If you do not provide a constructor, the compiler will create a default constructor with the super call to the parent class.
If you do provide a constructor without putting in a super call, the compiler will put in a super call to the parent class default constructor.
Regardless, of whether the superclass constructor is called implicitly or explicitly, the process of calling superclass constructors continues until the Object constructor is called. At this point, all the constructors within the hierarchy execute beginning with the Object constructor.
Click on "Runestone Academy" below to open the required reading that is listed.
Runestone Academy: AP CSA – Java Review Links to an external site.
- 11.9 – Using Super to Call an Overridden Method
PracticeIt!
-
Go to the PracticeIt website Links to an external site..
- Log into account.
- Click on Start Practicing!
- Go to the most recent edition.
- Click on Chapter 9: Inheritance and Interfaces
- Complete Self-Check: 9.3
IMAGES CREATED BY GAVS