Java Reference
In-Depth Information
5. public NonFictionBook(String subject, String ISBN) {
6. super(ISBN);
7. this.subject = subject;
8. }
9.
10. public NonFictionBook(String subject) {
11. this.subject = subject;
12. }
13. }
These two class definitions are not numbered sequentially because they
cannot be defined in the same source file.
The call to
super
on line 6 of
NonFictionBook.java
invokes the
Book
constructor on line
7 of
Book.java
, passing in a
String
that gets stored in a fi eld of
Book
. Study the following
code and try to determine its output:
4. NonFictionBook x = new NonFictionBook(“American History”, “123-45”);
5. NonFictionBook y = new NonFictionBook(“Greek Mythology”);
6. System.out.println(x.ISBN);
7. System.out.println(y.ISBN);
Executing this code results in the following sequence of events:
1.
The string “
123-45
” in the
new
statement is passed into the constructor on line 5 of
NonFictionBook
.
2.
On line 6 of
NonFictionBook
, the call to
super
passes the
String
to line 7 of
Book
.
3.
On line 8 of
Book
, the
String
is assigned to the
ISBN
field declared on line 5. Therefore,
x.ISBN
is “
123-45
”.
4.
The
new
statement for
y
invokes the
NonFictionBook
constructor on line 10 of
NonFictionBook
.
5.
Because no explicit call to
super
appears in that constructor, the no-argument
constructor of
Book
on line 11 is invoked, which assigns the
ISBN
field to “
-1
”.
Therefore,
y.ISBN
is “
-1
”.
6.
The
println
statements output the following:
123-45
-1
Search WWH ::
Custom Search