While reading the docs on apex properties I noticed that you can use access modifiers on class instance property getters / setters. While playing around with private setters and running a few examples in anonymous apex, I noticed some confusing behavior:
public class Person {
public Person() {
this.name = '';
}
public String name { get; private set; }
}
Person peter = new Person();
peter.name = 'Peter'; // I expected this to throw a private property error
System.debug(peter.name); // Outputs 'Peter' to the console
The instance variable name
has a public getter and a private setter. I expected this property to be accessible when referenced by client code (e.g. new Person().name) but to throw some type of method access control error when the client attempts to set its value (e.g. new Person().name = 'Ricky').
In the example above, even though the name
setter is private, the name property of the peter
object is still being modified via the setter, bypassing the private
access modifier.
Am I missing something here? Why can I set the name
property even though it has a private setter?