题
我来自 php 世界。您能解释一下 getter 和 setter 是什么,并举一些例子吗?
解决方案
是不是真的需要这个教程。阅读上封装
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;
}
其他提示
在爪哇getter和setter是完全普通功能。这使得他们的getter或setter方法的唯一事情是惯例。一个foo的调用getter时的getFoo和setter方法称为setFoo。在一个布尔值的情况下,调用getter时isFoo。它们还必须具有特定的声明,如图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;
}
}
之所以使用getter和setter方法,而不是使你的会员公开的是,它能够改变实现不改变接口。此外,许多工具和使用反射来检查对象的工具包只接受有getter和setter对象。 的JavaBeans 的例如必须具有getter和setter以及一些其他要求。
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);
}
}
当您运行程序时,程序会在主电源中启动,
- 对象c被创建
- 功能
setTime()
由对象 c 调用 - 变量
time
设置为传递的值 - 功能
getTime()
由对象 c 调用 - 时间返回
- 它将传递到
tod
和tod
打印出来
您也可能需要阅读 “的为什么获取和设置方法是恶”:
虽然getter / setter方法在Java中是司空见惯的,它们没有特别的面向对象的(OO)。事实上,他们可能会损坏你的代码的可维护性。此外,无数的获取和设置方法的存在是红旗该程序是不一定很好从OO透视设计。
这文章解释了为什么你不应该使用的getter和setter(以及何时可以使用它们),并提出了一种设计方法,将帮助你摆脱的getter / setter的心态。
1.最好的 getter/setter 都是聪明的。
这是来自 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)
我经常使用这些,因为它们是 惊人的. 。当我喜欢我的编码+动画时,我会使用它。例如,制作一个处理以下内容的 setter Number
它会在您的网页上显示该号码。当使用 setter 时,它使用 a 将旧数字动画化为新数字 中间人. 。如果初始数字为 0 并且将其设置为 10,那么您会看到数字从 0 快速翻转到 10,比方说,半秒。用户喜欢这些东西并且创造起来很有趣。
2.PHP 中的 getter/setter
来自软件的示例
<?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;
}
}
?>
引用:
下面是解释在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();
}
}