Java Reference
In-Depth Information
explicitly defi nes its own constructor.) Using this version of the Book class, the following
FictionBook class does not compile:
public class FictionBook extends Book {
public String mainCharacter;
public FictionBook(String m) {
mainCharacter = m;
}
}
The following compiler error is generated:
FictionBook.java:4: cannot find symbol
symbol : constructor Book()
location: class Book
public FictionBook(String m) {
^
To fi x this compiler error, a call to super that passes in a String must explicitly appear
on the fi rst line of code in the constructor of FictionBook , even if it is not clear what
value to pass to the Book constructor. The following constructor in FictionBook compiles
successfully:
public FictionBook(String m) {
super(“-1”);
mainCharacter = m;
}
Instance Initializers
An instance initializer is a block of code declared in a class that executes for each new
instance of the class. An instance initializer executes immediately after the parent class
constructor fi nishes and before the body of the class constructor executes. A class can have
multiple instance initializers and they are executed in the order they appear in the source
fi le. Instance initializers are not members of a class like fi elds and methods are. You cannot
explicitly invoke an instance initializer because it does not have a name.
The following Book class contains an instance initializer on lines 11 to 15:
1. public class Book {
2. public String title;
3. public Person author;
Search WWH ::




Custom Search