Re: [問題] 多形問題
※ 引述《pelicanper (派立肯)》之銘言:
: There are huge differences between:
: student.name (without information hiding)
: student.getName() (with information hideing)
: When outside codes want to change the name temporarily, for example,
: in some situations you want to print out "王先生" instead of "王小明".
: //case without information hiding
: //what happens if you forget to change it back?
: String tempName = student.name;
: tempName = "王先生"; (student.name also changed)
這個例子不對,這裡 student.name 並不會跟著改變!
: //case with information hiding
: //student.name is safe
: String tempName = student.getName();
: tempName = "王先生"; (student.name never changes)
: A good programmer usually uses private, at least proteted, to secure
: the value of variables.
: When I studied JAVA programming in school, it would be zero mark
: if I wrote codes without information hiding...
我的例子長這樣:
public class BadSchool {
public List<String> studentNames;
}
public class GoodSchool {
private List<String> studentNames;
public List<String> getStudentNames () {
return Lists.newArrayList(studentNames); // defensive copy
}
}
在 GoodSchool 裡,因為外部經由 getter 拿到的其實是 copy,所以沒有辦
法直接改到內部的值,也就保護了內部的值不會被不預期地改變。使用 getter
的好處就是,你不見得要直接回傳 member field,你可以同時做一些別的事,
讓自己的 code 更有彈性。
--
Just because you deserve this
doesn't mean they're gonna give it to you.
Sometimes you gotta take what's yours.
── Kenny Ray Carter
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 71.217.88.212
推
11/03 03:36, , 1F
11/03 03:36, 1F
→
11/03 05:50, , 2F
11/03 05:50, 2F
→
11/03 05:52, , 3F
11/03 05:52, 3F
討論串 (同標題文章)