Answer the question
In order to leave comments, you need to log in
When should the visibility of a method be set to private, and when should it be protected?
Let's say I'm designing a class. How do I know when a method's visibility should be private
, and when it should be protected
? In other words, how can I know in advance that another programmer will never need to override this method?
Answer the question
In order to leave comments, you need to log in
If you don’t explicitly need to make it protected (for example, by overriding which method, you will allow the user to modify the behavior) - make it private. Just in case, making protected is at least strange, it’s the same as making everything public just in case. In general, if you are writing a library, then just as you define what will be the public interface (public) and what will be the implementation (private), enter another entity - the interface for the heirs. With this division (interface for everyone / interface for successors / implementation details), everything should become more or less clear.
private - this method is needed only by the current class and ancestors should not climb into it, it is self-sufficient
protected - allow ancestors to override / use the method directly
They already answered well here, but I’ll clarify: the difference is in visibility / accessibility zones, and this is very dependent on the language. Private is a local scope (for example, limited by a unit, file, module, namespace - for different languages), that is, it is available from the code that is one logical whole with this class. And Protected is the opposite, visibility from all classes generated from it, no matter what files, modules and units they are in.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question