What are the uses of getter/setters in Java? [dupl

2019-01-12 05:08发布

This question already has an answer here:

I have seen member variables given a private modifier and then using getter/setter methods just to set and get the values of the variable (in the name of standardization).

Why not then make the variable public itself (Other than cases like spring framework which depends on getter/setters for IOC etc). It serves the purpose.

In C# I have seen getter/setter with Capitalization of the member variable. Why not make the variable public itself?

15条回答
来,给爷笑一个
2楼-- · 2019-01-12 05:38

Encapsulation

You also mentioned C# properties. These are really just getters/setters under the hood, but with a more concise syntax.

查看更多
戒情不戒烟
3楼-- · 2019-01-12 05:39

In order to get a stable API from the first shot. The Java gurus thought that if later on, you might want to have some extra logic when setting/getting an instance member, you don't want to break existing API by replacing public fields with public methods. This is the main reason in Java.

In the case of C#, public properties are used instead of public fields because of binary interface compatibility. Someone asked a similar question right here, on SO.

So, it's all about encapsulating some logic while still preserving interface for... future proofing.

查看更多
小情绪 Triste *
4楼-- · 2019-01-12 05:40

You'd need encapsulate those attributes if there are constraints for example or to make general validity checks or post events on changes or whatever. The basic use is hiding the attribute from the "outer world".

查看更多
登录 后发表回答