获得者和安装者如何工作?

我来自PHP世界。 你能解释一下吸气剂和吸附剂是什么,可以给你一些例子吗?

教程不是真的需要这个。 阅读封装

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; } 

在Java中,getter和setter是完全普通的函数。 使得他们的getter或setters是唯一的约定。 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而不是公开你的成员的原因是它可以在不改变接口的情况下改变实现。 另外,使用reflection来检查对象的许多工具和工具包只接受具有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); } } 

当你运行程序时,程序开始在主电源,

  1. 对象c被创build
  2. 函数setTime()被对象c调用
  3. 可变time设置为通过的值
  4. 函数getTime()被对象c调用
  5. 时间被返回
  6. 它会过去,并打印出来

你也可能想读“ 为什么吸气和制定者的方法是邪恶的 ”:

尽pipegetter / setter方法在Java中很常见,但并不是特别面向对象(OO)。 事实上,他们可能会损害你的代码的可维护性。 此外,无数的getter和setter方法的出现是一个红旗,从OO的angular度来看,该程序不一定是很好的devise。

这篇文章解释了为什么你不应该使用getter和setter(以及什么时候可以使用它们),并且build议一种devise方法来帮助你摆脱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(ob) // Runs the getter, which yields a + 1 (which is 1) 

我已经用了很多,因为它们很棒 。 当我喜欢我的编码+animation时,我会使用它。 例如,制作一个处理器,处理在您的网页上显示该号码的号码。 当使用setter时,它使用镊子将旧号码animation到新号码。 如果初始数字为0,并将其设置为10,则会看到数字快速从0跳到10,比如说,半秒。 用户喜欢这个东西,创造乐趣。

2.在PHP中获取/设置器

来自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:

例子是在这里expalin在'java'中使用getter和setter这个最简单的方法。 可以通过更直接的方式来做到这一点,但getter和setter在inheritance中使用子类中的父类的私有成员时有一些特殊的地方。 你可以通过使用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(); } }