作者eieio (好多目标)
看板java
标题Re: [问题] 多形问题
时间Fri Nov 2 16:04:47 2012
※ 引述《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
1F:推 pelicanper:Did you read comments?...@@ 11/03 03:36
2F:→ eieio:I did. I agree with information hiding. 11/03 05:50
3F:→ eieio:But the example you gave didn't work as you thought 11/03 05:52