When to use Protected modifier
When to use Protected modifier
From the developer guides we have the following definition:
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.
However, I am still unsure when to use this and how it differs from the public modifier.
1 Answer
1
The protected
access modifier is much more like private
than public
. In fact, for a class which is not virtual
nor abstract
, this access modifier would be the same as private (though it's not allowed). However, once you allow extension of the class, you can then see it in overriding implementations.
protected
private
public
virtual
abstract
public class Class1
protected void foo()
// this access would just be the same as private
// however, the class will not compile
public virtual class Class2
protected void foo()
// now this class will compile
// this method can only be seen by extensions of this class
public class Class3 extends Class2
public static bar()
// cannot see the foo method here because the method is static
// the below line will cause compile fail
new Class1().foo();
public class Class4 extends Class2
public void baz()
// now that you are within an instance which extends the definition,
// you are able to see the method
this.foo();
Thanks for contributing an answer to Salesforce Stack Exchange!
But avoid …
To learn more, see our tips on writing great answers.
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.