You still need to write a setter. Please also note that if your variable is private, so is the getter. If you want to make the property only writable within the class, here is how I would do it:
public with sharing class MyClass
{
public Integer myProperty { get; private set; }
public MyClass(Integer value)
{
myProperty = value;
}
}
If you want to make the property only writable from your constructor, you can instead use the final
keyword. Note that attempts at reassignment will cause a run-time error, not compile-time.
public with sharing class MyClass
{
final Integer property;
public MyClass(Integer property) { this.property = property; }
public void increment(Integer value)
{
property += value; // will cause run-time error
}
}
Using the final Keyword
You can use the final keyword to modify variables.
- Final variables can only be assigned a value once, either when you declare a variable or inside a constructor. You must assign a value to it in one of these two places.
- Static final variables can be changed in static initialization code or where defined.
- Member final variables can be changed in initialization code blocks, constructors, or with other variable declarations.
- To define a constant, mark a variable as both static and final.
- Non-final static variables are used to communicate state at the class level (such as state between triggers). However, they are not shared across requests.
- Methods and classes are final by default. You cannot use the final keyword in the declaration of a class or method. This means they cannot be overridden. Use the virtual keyword if you need to override a method or class.