What is the example situation where protected is preferred, but not public? Can someone can elaborate it with example? I have already seen the chat for public, private and protected (see here).
A primary use of protected
is cases where a subclass overrides a method that provides some internal details that you don't want to expose to the outside classes. Consider a class like
class BaseAlgorithm {
run() {
commonStepOne();
subclassSpecificStepTwo();
}
protected abstract subclassSpecificStepTwo();
}
No one should be calling subclassSpecificStepTwo
, so it wouldn't make sense to have it public.