im from the php world. are there good tutorials explaining what getters and setters are and could give you some examples?
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 void Dummy() {}
public void 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.
I think the Wikipedia article can be a good start.
Most IDEs will provide the feature of generating getters/setters for existing member variables.
Tutorial is not really required for this. Read up on encapsulation
private string myField; //access to this is restricted
public sting getMyField()
{
//include validation, logic, logging or whatever you like here
return this.myField;
}
public void setMyField(string value)
{
//include more logic
this.myField = value;
}
This is a good place to start in addition to the links and explanations provided by the other posters: "Learning the Java Language - Objects & Classes".
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.