Java Reference
In-Depth Information
If you initialize instance variables in this way, you may or may not want to define
constructors. But if you do define any constructors, it is usually best to define a no-
argument constructor even if the body of the no-argument constructor is empty.
EXAMPLE: A Pet Record Class
Display 4.15 contains another example of a class definition. In this case, the objects of the
class represent pet records consisting of the pet's name, age, and weight. Notice the similari-
ties and differences between the constructors and the mutator methods (the ones whose
names begin with set ). They both set instance variables, but they are used differently. The
constructors are used to create and initialize new objects of the class. However, after the
object is created using a constructor and new , any changes to the object are performed by the
mutator methods such as set or setAge . This is illustrated by the program in Display 4.16.
It would be possible to use constructors in place of the mutators, such as the method
set . For example, the program in Display 4.16 would produce the same dialogue if you
replace the line
usersPet.set(name, age, weight);
with
usersPet = new Pet(name, age, weight);
However, this use of constructors is a bad idea.
The following mutator method invocation simply changes the values of the instance
variables of the object named by usersPet :
usersPet.set(name, age, weight);
However, the following use of a constructor creates a completely new object, which is a
much less efficient process than just changing the values of some instance variables:
usersPet = new Pet(name, age, weight);
Display 4.16 A Class for Pet Records (part 1 of 4)
1 /**
2 Class for basic pet records: name, age, and weight.
3 /
4 public class Pet
5{
6 private String name;
7 private int age;//in years
8
private double weight;//in pounds
9
Search WWH ::




Custom Search