getter / setter在Java中有什么用处? [英] What are the uses of getter/setters in Java?

查看:200
本文介绍了getter / setter在Java中有什么用处?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到成员变量赋予一个私有修饰符,然后使用getter / setter方法来设置和获取变量的值(以标准化名称)。

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).

为什么不使变量公开本身(除了像spring框架这样取决于getter / setters为IOC等)。它服务于目的。

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.

在C#中,我已经看到getter / setter与成员变量的大小写。为什么不让变量公开?

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

推荐答案

为了从第一个获得稳定的API 射击。 Java gurus认为,如果以后,在设置/获取实例成员时可能需要一些额外的逻辑,则不希望通过将公共字段替换为公共方法来打破现有API 。这是Java中的主要原因。

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.

在C#的情况下,由于二进制接口兼容性,使用公共属性而不是公共字段。有人在这里请SO 一个类似问题

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.

这篇关于getter / setter在Java中有什么用处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆