Java Reference
In-Depth Information
if
(someText.equals(theSameText))
System.out.println("5 TRUE");
someText
#
new
String("another text");
// only changes the reference
if
(theSameObject.equals(theSameText))
System.out.println("6 TRUE");
While variables' lifetimes are linked to that of the method where they are defined,
this is not true for the objects created in a method and referenced by object
variables defined in it. A variable of a method exists only while a thread of control
traverses the method. Attributes are used to store values of references that
must be kept beyond the end of a method. Object attributes have the same
characteristics as object variables.
The
name
attribute is initialized once and for ever by the constructor; its
value can be read by means of the
name()
method (Sidebar 4.2). Such an
approach can be generalized in the form of an idiom: read-only attribute.
Value
is a public attribute, but there are constraints on the values it can
assume, in particular it can assume only the values allowed by the type. To
ensure that only allowed values can be assigned, it is implemented as a
private attribute. Two methods are provided to get and set its value. The
getter
method is analogous to the one used for the
name
read-only attribute.
The
setter
method checks with the
type
if the new value is allowed; if it is not
then an
IllegalArgumentException
is raised. This approach can be generalized
as the constrained attribute idiom.
public class
Feature {
private
String name;
private
String value;
private
FeatureType type;
public
Feature(String name, String value, FeatureType
type){
this
.name
#
name;
this
.value
#
value;
this
.type
#
type;
}
public
String name() {
return
name; }
public
String value() {
return
value; }
public
void value(String newValue){
if
(type.isAllowed(newValue))
value
#
newValue;
else
throw new
IllegalArgumentException
("value"
!
newValue
!
" not valid for attribute "
!
name);
}
}