¿Cómo funcionan los getters y setters?


Soy del mundo php. ¿Podría explicar qué son los getters y setters y podría darle algunos ejemplos?

Author: Richard Tingle, 2010-01-10

6 answers

El tutorial no es realmente necesario para esto. Leer sobre encapsulación

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;
}
 119
Author: Paul Creasey,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-04-29 12:35:40

En Java los getters y setters son funciones completamente ordinarias. Lo único que los hace getters o setters es la convención. Un getter para foo se llama getFoo y el setter se llama setFoo. En el caso de un booleano, el getter se llama isFoo. También deben tener una declaración específica como se muestra en este ejemplo de un getter y setter para 'name':

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

La razón para usar getters y setters en lugar de hacer que sus miembros sean públicos es que hace posible cambiar implementación sin cambiar la interfaz. Además, muchas herramientas y conjuntos de herramientas que usan reflexión para examinar objetos solo aceptan objetos que tienen getters y setters. JavaBeans por ejemplo, debe tener getters y setters, así como algunos otros requisitos.

 36
Author: Mark Byers,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-12-14 12:02:13
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);  
 }
}  

Cuando se ejecuta el programa, el programa se inicia en red,

  1. se crea el objeto c
  2. la función setTime() es llamada por el objeto c
  3. la variable time se establece en el valor pasado por
  4. la función getTime() es llamada por el objeto c
  5. se devuelve la hora
  6. Pasará a tod y tod se imprimirá
 12
Author: user3137648,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-06-11 06:30:50

Es posible que también desee leer " Por qué los métodos getter y setter son malos":

Aunque los métodos getter/setter son comunes en Java, no están particularmente orientados a objetos (OO). De hecho, pueden dañar la capacidad de mantenimiento de su código. Además, la presencia de numerosos métodos getter y setter es una señal de que el programa no está necesariamente bien diseñado desde una perspectiva de OO.

Este artículo explica por qué no debe usar getters y setters (y cuándo usted puede usarlos) y sugiere una metodología de diseño que le ayudará a romper con la mentalidad de getter/setter.

 7
Author: superfav,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-01-10 18:33:28

1. Los mejores getters / setters son inteligentes.

Aquí hay un ejemplo de javascript de mozilla:

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)

Los he usado MUCHO porque son impresionantes . Lo usaría cuando me pongo elegante con mi codificación + animación. Por ejemplo, crea un setter que trate con un Number que muestre ese número en tu página web. Cuando se usa el setter, anima el número antiguo al nuevo usando un tweener . Si el número inicial es 0 y lo establece en 10, entonces lo haría ver los números voltear rápidamente de 0 a 10 durante, digamos, medio segundo. A los usuarios les encanta este material y es divertido de crear.

2. Getters / setters en php

Ejemplo de 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;
  }
}
?>

Citas:

 2
Author: Jacksonkr,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:18:25

Ejemplo está aquí para expalin esta forma más simple de usar getter y setter en 'java' . uno puede hacer esto de una manera más directa, pero getter y setter tienen algo especial que es cuando se usa un miembro privado de la clase padre en la clase hijo en herencia. puede hacerlo posible mediante el uso de getter y 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();
        }

    }
 0
Author: Bashir ahmad,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-06 14:03:18