Java Reference
In-Depth Information
Self-Test Exercises (continued)
<Details not shown.>
}
public void doStuff()
{
<Details not shown.>
}
}
Which of the following are legal in a program that uses this class?
YourClass anObject = new YourClass(42, 'A');
YourClass anotherObject = new YourClass(41.99, 'A');
YourClass yetAnotherObject = new YourClass();
yetAnotherObject.doStuff();
YourClass oneMoreObject;
oneMoreObject.doStuff();
oneMoreObject.YourClass(99, 'B');
26. What is a no-argument constructor? Does every class have a no-argument
constructor? What is a default constructor?
Default Variable Initializations
Local variables are not automatically initialized in Java, so you must explicitly initialize
a local variable before using it. Instance variables, on the other hand, are automatically
initialized. Instance variables of type boolean are automatically initialized to false .
Instance variables of other primitive types are automatically initialized to the zero of
their type. Instance variables of a class type are automatically initialized to null , which
is a kind of placeholder for an object that will be filled in later. We will discuss null in
Chapter 5. Although instance variables are automatically initialized, we prefer to always
explicitly initialize them in a constructor, even if the initializing value is the same as the
default initialization. That makes the code clearer.
An Alternative Way to Initialize Instance Variables
Instance variables are normally initialized in constructors, which is where we prefer to
initialize them. However, there is an alternative. You can initialize instance variables
when you declare them in a class definition, as illustrated by the following:
public class Date
{
private String month = "January";
private int day = 1;
private int year = 1000;
 
Search WWH ::




Custom Search