9

I want to create a public getter and private setter for private property. How to do that using shorthand (not Java-like separate methods at the bottom of class)?

Here's what I'm trying to do (not working, getting "Can't declare public getter on private property"):

private Decimal number { public get; set; }
  • Just curious, if you want to make read and write access to the property public, why does the property still need to be kept private? – Andrew Fawcett Feb 4 '14 at 13:36
  • 1
    I formed my question not very well, sorry. I wanted private setter and public getter – justasd Feb 4 '14 at 13:43
  • Ah ok, I've added my answer then. – Andrew Fawcett Feb 4 '14 at 13:49
  • You should also consider clarifying your question for future readers. – Andrew Fawcett Feb 4 '14 at 13:50
  • I edited my post and will focus more on clarifying questions in the future. Thanks a lot for great answer! – justasd Feb 4 '14 at 15:54
21

If you want a private setter and public getter define your property like so...

public Decimal myNumber { get; private set; }

You can read more about Apex Properties and access modifiers here.

  • Or, stated generically, the access modifier of the variable must be the greater of the access modifiers for the accessor and mutator. – sfdcfox Feb 4 '14 at 15:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.