Java Reference
In-Depth Information
Using
super
in Constructors
Similar to how you can use the
this
keyword to invoke another constructor in the same
class, you can use the
super
keyword to invoke a constructor in the parent class. Using
super
allows the child class to choose which parent class constructor gets executed. As
with the
this
keyword, any calls to
super
must be the fi rst line of code in your constructor
or the code will not compile.
The
super
Keyword
Don't confuse the use of
super
in a constructor with the
super
keyword that represents
the reference to an object's parent. Using
super
in a constructor is a different, unrelated
use of the
super
keyword.
Let's look at an example. The following
NonFictionBook
class is a child of the
Book
class
and invokes one of the constructors in
Book
using the
super
keyword on line 6:
1. //Book.java
2. public class Book {
3. public String title;
4. public Person author;
5. public String ISBN;
6.
7. public Book(String ISBN) {
8. this.ISBN = ISBN;
9. }
10.
11. public Book() {
12. title = “Unknown”;
13. author = null;
14. ISBN = “-1”;
15. }
16.}
1. //NonFictionBook.java
2. public class NonFictionBook extends Book {
3. public String subject;
4.
Search WWH ::
Custom Search