Java Reference
In-Depth Information
public class Test {
public static void main(String[] args) {
Student student = new Student( 111223333 , "John" );
java.util.Date dateCreated = student.getDateCreated();
dateCreated.setTime( 200000 ); // Now dateCreated field is changed!
}
}
For a class to be immutable, it must meet the following requirements:
All data fields must be private.
There can't be any mutator methods for data fields.
No accessor methods can return a reference to a data field that is mutable.
Interested readers may refer to Supplement III.AB for an extended discussion on immutable
objects.
10.1
If a class contains only private data fields and no set methods, is the class immutable?
Check
10.2
If all the data fields in a class are private and primitive types, and the class doesn't
contain any set methods, is the class immutable?
Point
10.3
Is the following class immutable?
public class A {
private int [] values;
public int [] getValues() {
return values;
}
}
10.3 The Scope of Variables
The scope of instance and static variables is the entire class, regardless of where the
variables are declared.
Key
Point
Chapter 5, Methods, discussed local variables and their scope rules. Local variables are
declared and used inside a method locally. This section discusses the scope rules of all the
variables in the context of a class.
Instance and static variables in a class are referred to as the class's variables or data fields .
A variable defined inside a method is referred to as a local variable . The scope of a class's
variables is the entire class, regardless of where the variables are declared. A class's variables
and methods can appear in any order in the class, as shown in Figure 10.1a. The exception is
when a data field is initialized based on a reference to another data field. In such cases, the
class's variables
public class Circle {
public double findArea() {
return radius * radius * Math.PI;
public class F {
private int i;
private int j = i + 1 ;
}
}
private double radius = 1 ;
}
(a) The variable radius and method findArea() can be
declared in any order.
(b) i has to be declared before j because j 's initial value is
dependent on i .
F IGURE 10.1
Members of a class can be declared in any order, with one exception.
 
 
Search WWH ::




Custom Search