Java getter 和 setter 是如何工作的?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2036970/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do getters and setters work?
提问by ajsie
I'm from the php world. Could you explain what getters and setters are and could give you some examples?
我来自 php 世界。你能解释一下什么是 getter 和 setter 吗?能给你一些例子吗?
采纳答案by Paul Creasey
Tutorial is not really required for this. Read up on encapsulation
教程并不是真正需要的。阅读封装
private String myField; //"private" means access to this is restricted
public String getMyField()
{
//include validation, logic, logging or whatever you like here
return this.myField;
}
public void setMyField(String value)
{
//include more logic
this.myField = value;
}
回答by Mark Byers
In Java getters and setters are completely ordinary functions. The only thing that makes them getters or setters is convention. A getter for foo is called getFoo and the setter is called setFoo. In the case of a boolean, the getter is called isFoo. They also must have a specific declaration as shown in this example of a getter and setter for 'name':
在 Java 中 getter 和 setter 是完全普通的函数。使它们成为 getter 或 setter 的唯一因素是约定。foo 的 getter 称为 getFoo,setter 称为 setFoo。在布尔值的情况下,getter 称为 isFoo。它们还必须有一个特定的声明,如这个“name”的 getter 和 setter 示例所示:
class Dummy
{
private String name;
public Dummy() {}
public Dummy(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
}
The reason for using getters and setters instead of making your members public is that it makes it possible to change the implementation without changing the interface. Also, many tools and toolkits that use reflection to examine objects only accept objects that have getters and setters. JavaBeansfor example must have getters and setters as well as some other requirements.
使用 getter 和 setter 而不是让成员公开的原因是,它可以在不更改接口的情况下更改实现。此外,许多使用反射来检查对象的工具和工具包只接受具有 getter 和 setter 的对象。例如,JavaBeans必须有 getter 和 setter 以及其他一些要求。
回答by superfav
You may also want to read "Why getter and setter methods are evil":
您可能还想阅读“为什么 getter 和 setter 方法是邪恶的”:
Though getter/setter methods are commonplace in Java, they are not particularly object oriented (OO). In fact, they can damage your code's maintainability. Moreover, the presence of numerous getter and setter methods is a red flag that the program isn't necessarily well designed from an OO perspective.
This article explains why you shouldn't use getters and setters (and when you can use them) and suggests a design methodology that will help you break out of the getter/setter mentality.
尽管 getter/setter 方法在 Java 中很常见,但它们并不是特别面向对象 (OO)。事实上,它们会损害代码的可维护性。此外,大量 getter 和 setter 方法的存在是一个危险信号,表明从面向对象的角度来看,程序不一定设计得很好。
本文解释了为什么不应该使用 getter 和 setter(以及何时可以使用它们),并提出了一种设计方法,可以帮助您摆脱 getter/setter 的心态。
回答by user3137648
class Clock {
String time;
void setTime (String t) {
time = t;
}
String getTime() {
return time;
}
}
class ClockTestDrive {
public static void main (String [] args) {
Clock c = new Clock;
c.setTime("12345")
String tod = c.getTime();
System.out.println(time: " + tod);
}
}
When you run the program, program starts in mains,
当你运行程序时,程序在主电源中启动,
- object c is created
- function
setTime()
is called by the object c - the variable
time
is set to the value passed by - function
getTime()
is called by object c - the time is returned
- It will passe to
tod
andtod
get printed out
- 对象 c 被创建
- 函数
setTime()
被对象 c 调用 - 变量
time
设置为传递的值 - 函数
getTime()
被对象 c 调用 - 时间回来了
- 它将传递给
tod
并tod
打印出来
回答by Hymansonkr
1. The best getters / setters are smart.
1. 最好的 getter/setter 是聪明的。
Here's a javascript example from mozilla:
这是来自 mozilla 的 javascript 示例:
var o = { a:0 } // `o` is now a basic object
Object.defineProperty(o, "b", {
get: function () {
return this.a + 1;
}
});
console.log(o.b) // Runs the getter, which yields a + 1 (which is 1)
I've used these A LOT because they are awesome. I would use it when getting fancy with my coding + animation. For example, make a setter that deals with an Number
which displays that number on your webpage. When the setter is used it animates the old number to the new number using a tweener. If the initial number is 0 and you set it to 10 then you would see the numbers flip quickly from 0 to 10 over, let's say, half a second. Users love this stuff and it's fun to create.
我已经使用了很多,因为它们很棒。当我喜欢我的编码 + 动画时,我会使用它。例如,制作一个 setter 来处理Number
在您的网页上显示该数字的 。当使用 setter 时,它使用tweener将旧数字动画化为新数字。如果初始数字为 0 并且您将其设置为 10,那么您会看到数字从 0 快速翻转到 10,比方说,半秒。用户喜欢这些东西,而且创造起来很有趣。
2. Getters / setters in php
2. php中的getter/setter
Example from sof
来自 sof 的例子
<?php
class MyClass {
private $firstField;
private $secondField;
public function __get($property) {
if (property_exists($this, $property)) {
return $this->$property;
}
}
public function __set($property, $value) {
if (property_exists($this, $property)) {
$this->$property = $value;
}
return $this;
}
}
?>
citings:
引用:
回答by Bashir ahmad
Here is an example to explain the most simple way of using getter and setter in java. One can do this in a more straightforward way but getter and setter have something special that is when using private member of parent class in child class in inheritance. You can make it possible through using getter and setter.
这里以一个例子来解释在java中使用getter和setter的最简单的方法。可以以更直接的方式做到这一点,但 getter 和 setter 有一些特殊之处,那就是在继承的子类中使用父类的私有成员时。您可以通过使用 getter 和 setter 来实现。
package stackoverflow;
public class StackoverFlow
{
private int x;
public int getX()
{
return x;
}
public int setX(int x)
{
return this.x = x;
}
public void showX()
{
System.out.println("value of x "+x);
}
public static void main(String[] args) {
StackoverFlow sto = new StackoverFlow();
sto.setX(10);
sto.getX();
sto.showX();
}
}