function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Engine ForceEngine Force 

Private set

Do you have examples on how public string str { get; private set;}? I cannot find documentation on how to use private set. Does it mean it can only be set inside a method in the current class?

 

Thanks!

Best Answer chosen by Admin (Salesforce Developers) 
ForcepowerForcepower
Correct. A private setter allows modification only within that class's code. A public setter will allow other components outside the class to modify it.

All Answers

ForcepowerForcepower
Correct. A private setter allows modification only within that class's code. A public setter will allow other components outside the class to modify it.
This was selected as the best answer
Engine ForceEngine Force

What about protected set? Does it mean only sub-classes can set it? What's the use case that requires using protected set?

 

And protected method or variables? There is no clear definition on how to use them.

public virtual class c1 {

    protected string str;

    public virtual class c2 {

       protected string str2;

    }

    public class c3 extends c2 {

       protected string str3;

    }

}

 

Also in the online article "OuterClass", it says

// Illegal - cannot call protected method externally
// new OuterClass.ConcreteChildClass().method2();

 

But this actually compiles fine. Any ideas?

ForcepowerForcepower
Yes - protected methods and instance variables are like private but are also available for direct access by sub-classes. The rationale here is that a sub class can access these like its own variables/methods unless you want the base class to encapsulate certain state or behavior.