java中getter的意义,getter / setter在Java中有什么用处?

博客讨论了在Java和C#中使用getter/setter而不是公开成员变量的原因。主要考虑是为了保持API的稳定性和未来可能的逻辑扩展,避免因后期修改导致的兼容性问题。在C#中,公共属性用于保持二进制接口兼容性。此外,getter/setter提供了一种封装逻辑的方式,以确保接口的未来证明。
摘要由CSDN通过智能技术生成

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?

解决方案

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值