用户自定义类
Employee类
The simplest form for a class definition in Java is:
class ClassName
{
constructor1
constructor2
. . .
method1
method2
. . .
field1
field2
. . .
}
We adopt the style that the methods for the class come first and the fields come at the end. Perhaps this, in a small way, encourages the notion of looking at the interface first and paying less attention to the implementation.
Be careful not to write accessor methods that return references to mutable objects. We violated that rule in our Employee class in which the getHireDay method returns an object of class Date:
class Employee{ . . . public Date getHireDay() { return hireDay; } . . . private Date hireDay;}
This breaks the encapsulation! Consider the following rogue code:
Employee harry = . . .;Date d = harry.getHireDay();double tenYearsInMilliSeconds = 10 * 365.25 * 24 * 60 * 60 * 1000;d.setTime(d.getTime() - (long) tenYearsInMilliSeconds);// let's give Harry ten years added seniority
The reason is subtle. Both d and harry.hireDay refer to the same object (see Figure 4-5). Applying mutator methods to d automatically changes the private state of the employee object!
If you need to return a reference to a mutable object, you should clone it first. A clone is an exact copy of an object that is stored in a new location. We discuss cloning in detail in Chapter 6. Here is the corrected code:
class Employee
{
. . .
public Date getHireDay()
{
return (Date) hireDay.clone();
}
. . .}
As a rule of thumb, always use clone whenever you need to return a copy of a mutable data field.

浙公网安备 33010602011771号