當我有一個變量,如exampleVariable
,我應該使用getExampleVariable()
和setExampleVariable(Object value)
並使exampleVariable
私人而不是ExampleClass.exampleVariable
和ExampleClass.exampleVariable = exampleObject;
?何時使用getter和setter?
即使getter和setter除了設置變量之外,我通常都會使用getter和setter。
是的。封裝決定了這個原理 – Dan
[Pick](http://stackoverflow.com/questions/565095/are-getters-and-setters-evil?rq = 1)[和](http://stackoverflow.com/questions/875033/getters-setters-in-java?rq=1)[選擇](http://stackoverflow.com/questions/875033/getters- setters-in-java?rq = 1)[a](http://stackoverflow.com/questions/10407877/what-is-the-point-of-getters-and-setters?lq=1)[重複]( http://stackoverflow.com/questions/1461598/what-is-the-point-of-setters-and-getters-in-java?lq=1)[question](http://stackoverflow.com/questions/ 11883454 /必要的吸氣劑方法?lq = 1)! – eboix
@丹雖然有人會將這個原理稱爲「信息隱藏」。 – Scooter