Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do getters and setters work?

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

like image 707
ajsie Avatar asked Jan 10 '10 12:01

ajsie


People also ask

How does getter and setter work in Java?

Getter returns the value (accessors), it returns the value of data type int, String, double, float, etc. For the program's convenience, getter starts with the word “get” followed by the variable name. While Setter sets or updates the value (mutators). It sets the value for any variable used in a class's programs.

How do you use setters and getters in two different classes?

To fix this, you need to pass a reference to the GetterAndSetter instance from class A to B . You can do this e.g. by passing it as a parameter to a method of B , or by creating a new instance of A in B and calling a method that provides an instance of GetterAndSetter .

Why setters and getters are evil?

Getter and setter methods (also known as accessors) are dangerous for the same reason that public fields are dangerous: They provide external access to implementation details. What if you need to change the accessed field's type? You also have to change the accessor's return type.


2 Answers

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; } 
like image 189
Paul Creasey Avatar answered Sep 30 '22 18:09

Paul Creasey


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.

like image 38
Mark Byers Avatar answered Sep 30 '22 18:09

Mark Byers