112

I'm from the php world. Could you explain what getters and setters are and could give you some examples?

Richard Tingle
  • 16,906
  • 5
  • 52
  • 77
ajsie
  • 77,632
  • 106
  • 276
  • 381
  • @yegor256 I understand your dog & ball analogy and I even support it, but what about when a "living organism" object stores the occasional primitive value eg an ID? What if you want to go a step beyond simple assignment but don't want to write a new class only to handle primitive values? – Jacksonkr Jan 06 '16 at 17:11

6 Answers6

129

Tutorial is not really required for this. Read up on encapsulation

private String myField; //"private" means access to this is restricted to the class.

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;
}
ublec
  • 172
  • 2
  • 15
Paul Creasey
  • 28,321
  • 10
  • 54
  • 90
  • 11
    so getter is just a method getting a private field and setter is setting a new field. thanks for the excellent explanation by code – ajsie Jan 10 '10 at 13:03
  • 1
    could you pass a parameter to a getter? – ajsie Jan 10 '10 at 13:35
  • 2
    noname: No and no. Getter is way for getting a value but NOT exposing the value contained in a field, that is if you call `someObj.getTime().setHour(5)` it should not affect `someObj`'s internal state. Also setters and getters *(accessors and mutators by their fancier name)* have a very strict method signature meaning that getter doesn't have any parameters. Methods in general should only do one thing anyway. – Esko Jan 10 '10 at 14:37
  • 4
    @noname: When simple things are given complex/big/abstract names, you have what is called a "design pattern".... And this is an example of the Recursive Concept Explanation Pattern I just invented ;-) – namespaceform Jan 15 '10 at 09:37
  • In eclipse, when you create a field, it shows you a warning and provides the option to create a getter and a setter for you, but in the getter, it does not use the `this` keyword, I wonder why. – qed Nov 02 '13 at 21:15
  • 3
    @qed: The `this` keyword is optional unless there is a conflict with something that has more specific scope. In the example you gave, the setter that is created will have a single parameter whose name matches the field name, hence `this.fieldName = fieldName`, is used to distinguish that the field is being assigned to rather than the parameter being assigned to its self as `fieldName = fieldname` would achieve. No such conflict exists in the getter. – Paul Creasey Nov 04 '13 at 07:00
  • what bothers me is that I wonder: would creating a function with a name like `"get"+capitalize()+"()"` *make* it a *getter*? are these names any special to Java? Could you link the specific part of the JLS if so? – n611x007 Dec 07 '13 at 09:21
  • Having an ActionScript and JS background I'm used to the fact that you can actually use a getter/setter like it were a property (like `this.myField = "Hello"`). Like naxa said; this way it's not so much a real getter/setter but more like a convention. If I'm correct I might just as well call the setter 'updateMyField' or something, right?! – Arno van Oordt Jun 26 '14 at 12:14
  • How to set 1000 values in setter method and get via getter method? It overwrites values, only 1000th is accessible. – Apurva Jul 27 '15 at 12:53
  • "Tutorial is not really required for this" I hate this response. How closed-minded. Obviously this approach is not desirable since it uses long-winded 'getThing' - where in other languages it's very possible and encouraged for syntactic sugar to use `= my.thing` to get or `my.thing=` to set. You assert nobody needs a tutorial, and assert that everybody should know that this is the case with Java... yet we're all discussing it on this page? How did we all get here then? – 1owk3y Jun 07 '18 at 15:33
39

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':

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. JavaBeans for example must have getters and setters as well as some other requirements.

Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
12
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,

  1. object c is created
  2. function setTime() is called by the object c
  3. the variable time is set to the value passed by
  4. function getTime() is called by object c
  5. the time is returned
  6. It will passe to tod and tod get printed out
GibboK
  • 71,848
  • 143
  • 435
  • 658
user3137648
  • 786
  • 1
  • 7
  • 10
10

You may also want to read "Why getter and setter methods are evil":

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.

Community
  • 1
  • 1
superfav
  • 1,041
  • 10
  • 11
3

1. The best getters / setters are smart.

Here's a javascript example from 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)

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.

2. Getters / setters in php

Example from 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:

Community
  • 1
  • 1
Jacksonkr
  • 31,583
  • 39
  • 180
  • 284
2

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.

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

    }
piet.t
  • 11,718
  • 21
  • 43
  • 52
Bashir ahmad
  • 241
  • 4
  • 12
  • I'm not going to downvote you (not worth the effort). Please be aware that (1) You have answerred on a **Java** question, where the program language _should_ be in Java. (2) If you want to post, ensure that the layout is done correctly. (3) Your use of encapsulation( getter (or accessor) and setters (or mutators)) is incorrect. Please look up what encapsulation means ... (Check the voted answer) – KarelG May 18 '17 at 08:48
  • 1
    @KarelG sorry i didn't read the tags. i updated it to java. thanks for realizing me. – Bashir ahmad May 18 '17 at 11:20