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
paul-lmipaul-lmi 

protected vs. private

could someone tell me (in English :) ) what the functional difference is between these two access modifiers?  from what I see, they both prevent access from outside classes, but what else?  what are the benefits of one vs. the other?

garybgaryb

Protected allows access in sub classes. So if you have a Vehicle class with a protected variable called colour, a Car class that extended Vehicle could operate on the colour variable. If the variable was private, you wouldn't be able to access it.

Anand@SAASAnand@SAAS

From the documentation:

 

private

This is the default, and means that the method or variable is accessible only within the Apex class in which it is defined. If you do not specify an access modifier, the method or variable is private.
protected
This means that the method or variable is visible to any inner classes in the defining Apex class. You can only use this access modifier for instance methods and member variables. Note that it is strictly more permissive than the default (private) setting, just like Java.

 

 

Michal KaparMichal Kapar
Update From the documentation:

protected
This means that the method or variable is visible to any inner classes in the defining Apex class, and to the classes that extend the defining Apex class. You can only use this access modifier for instance methods and member variables. Note that it is strictly more permissive than the default (private) setting, just like Java.

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_access_modifiers.htm