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.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Edmonton

Crossroads (UK TV series)