Skip to content

Instantly share code, notes, and snippets.

@SpOOnman
Created July 12, 2012 08:12
Show Gist options
  • Save SpOOnman/3096586 to your computer and use it in GitHub Desktop.
Save SpOOnman/3096586 to your computer and use it in GitHub Desktop.
Groovy private fields and methods are not private
class Person {
private String name
public String surname
private Person() {}
private String signature() { "${name?.substring(0, 1)}. $surname"}
public String toString() { "I am $name $surname"}
}
I am null null
I am Mike null
I am John null
I am John Foo
I am John Bar
J. Bar
public static void main(String[] args) {
def person = new Person() // constructor is private - compilation error in Java
println(person.toString())
person.@name = 'Mike' // access name field directly - compilation error in Java
println(person.toString())
person.name = 'John' // there is a setter generated by groovy
println(person.toString())
person.@surname = 'Foo' // access surname field directly
println(person.toString())
person.surname = 'Bar' // access auto-generated setter
println(person.toString())
println(person.signature()) // call private method - compilation error in Java
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment