While looking at the Java Core Technology (9th edition Chinese version), I saw a warning on page 113, "Be careful not to write a variable that returns a reference the accessor method for the object. Not seen before, the original date object is a mutable object . On the concept of mutable objects , I looked at the net, I think the mutable Object is the object that can change the value in the class without passing the domain change method . .
1 PackageCom.csst.sort;2 3 Importjava.util.Date;4 ImportJava.util.GregorianCalendar;5 6 Public classEmployee {7 PrivateString name;8 Private Doublesalary;9 PrivateDate Hireday;Ten One PublicEmployee (String N,DoubleSintYearintMonthintDay ) { AName =N; -Salary =s; -GregorianCalendar Calendar =NewGregorianCalendar (Year, month-1, day); theHireday =(Date) calendar.gettime (); - } - - Public Static voidMain (string[] args) { + -Employee Employee =NewEmployee ("Lele", 600, 1994, 10, 24); + ADate Date =Employee.gethireday (); at System.out.println (date); - -Date.settime (2000500000); - - System.out.println (date); - System.out.println (Employee.gethireday ()); in } - to Public voidRaisesalary (Doublebypercent) { + Doubleraise = This. Salary * bypercent/100; -Salary = This. Salary +raise; the } * $ PublicString GetName () {Panax Notoginseng returnname; - } the + Public voidsetName (String name) { A This. Name =name; the } + - Public Doublegetsalary () { $ returnsalary; $ } - - Public voidSetsalary (Doublesalary) { the This. Salary =salary; - }Wuyi the PublicDate Gethireday () { - returnHireday; Wu } - About Public voidSethireday (Date hireday) { $ This. Hireday =Hireday; - } - -}
Final Result:
Mon OCT 1994 00:00:00 CST
Sat Jan 11:41:40 CST 1970
Sat Jan 11:41:40 CST 1970
Note that Hireday has changed to change its get method to
Public Date Gethireday () {return (Date) Hireday.clone ();}
The result is:
Mon OCT 1994 00:00:00 CST
Sat Jan 11:41:40 CST 1970
Mon OCT 1994 00:00:00 CST
Note Do not write accessor methods that return references to mutable objects