question:When programming in Java, it is sometimes found that the private type is clearly defined in a class, and the result can be modified in other classes.
Code:
Class Employee
{
private String name;
private double salary;
Private Date Hireday;
Public Date Gethireday () {return
hireday
}}
Employee Harry = new Employee ("Harry", 75000,1987,12,15);
Date d = harry.gethireday ();
Double tenyearsinmilliseconds = 365.25 * * * * 1000;
D.settime (D.gettime ()-(long) tenyearsinmilliseconds);
System.out.println (Harry.gethireday ());
Arguably, hireday is defined as date, and Harry's employment date for the printout should be 1987, with the result being "Wed Dec 12:00:00 CST 1977". The reason for the mistake is very subtle. D and Harry. Hireday references the same object, changing its methods on the call automatically changes the private state of the employee object. This problem does not occur if you change the referenced salary in the main function, such as:
Class Employee
{
private String name;
private double salary;
Private Date Hireday;
Public double getsalary () {return
salary
}}
Double test = Harry.getsalary ();
Test = m;
SYSTEM.OUT.PRINTLN (test);
System.out.println (Harry.getsalary ());
Printed results: 50.0
75000.0
Workaround:If you need to return a reference to a Mutable object, you should first clone it. Object clone refers to a copy of an object that is stored in another location. Here is the modified code:
Class Employee
{
private String name;
private double salary;
Private Date Hireday;
Public Date Gethireday () {return
hireday.clone ();
}
}
Experience shows that if you need to return a copy of a mutable data field, you should use clone. Some students here may think that if the hireday with final modification, it is not solved the problem. However, in the case of mutable classes, the use of the final modifier may create confusion for the reader. Private final Date Hireday simply means that the object reference stored in the Hireday variable cannot be changed after the object is constructed, but does not mean that the Hireday object is a constant. Any method can invoke the SetTime change on an object that is referenced by Hireday. Reference: Java core technology.