Java Reference
In-Depth Information
4. public String ISBN;
5.
6. public Book(String ISBN) {
7. System.out.println(“Inside Book constructor”);
8. this.ISBN = ISBN;
9. }
10.
11. {
12. System.out.println(“Inside instance initializer”);
13. title = “Unknown”;
14. author = null;
15. }
16.}
The only syntax for an instance initializer is the curly braces. It is simply a block of code
located in a class defi nition with no name or special keyword to declare it. What is the
output of the following statement that instantiates a new Book object?
Book b = new Book(“888-999-7777”);
Because the instance initializer is invoked before the constructor, line 12 is displayed
before line 7 and the output is
Inside instance initializer
Inside Book constructor
Let's look at another example of an instance initializer. Study the following Vehicle and
Car class and try to determine the output of main in Car :
1. //Vehicle.java
2. public class Vehicle {
3. public int numOfWheels;
4.
5. public Vehicle(int n) {
6. System.out.println(“Inside Vehicle constructor”);
7. numOfWheels = n;
8. }
9. }
1. //Car.java
2. public class Car extends Vehicle {
Search WWH ::




Custom Search