Cool Groovy features 1 – no need for getters and setters

Consider the following Java code:

public class Customer{
private int id;
private String firstName;
private String lastName;
public void setId(int id){
this.id = id;
}
public void setFirstName(String firstName){
this.firstName = firstName;
}
public void setLastName(String lastName){
this.lastName = lastName;
}
public int getId(){
return id;
}
public String getFirstName(){
return firstName;
}
public String getLastName(){
return secondName;
}
}

In Groovy this would be defined as:

class Customer{
int id
String firstName
String lastName
}

In Groovy, if you don’t put an access modifier on an instance variable, it is assumed to be private,and Groovy generates public getters and setters for it. This means classes aren’t littered with getter and setter code, but just contain code that actually does stuff.

This entry was posted in Groovy and tagged . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

HTML tags are not allowed.

517,978 Spambots Blocked by Simple Comments