Java – what are the benefits of using protected variables on getters and setters?

See English answers > java protected fields vs public getters 7

Solution

Even if you use getters and setters (I personally do - I almost always keep fields confidential) this doesn't mean that protection becomes meaningless... It just means that you may protect getters and setters themselves rather than variables

If your question is actually about whether protected accessibility is useful, I would say - it usually makes sense to have a member that can only access subclasses More importantly, I sometimes use protected abstract methods called by superclasses, but they are inaccessible outside the hierarchy

For example, in the template method pattern, you may have a public method that can make some settings, call protected abstract methods, and then do some final work You don't want the abstract method to be public because you want to ensure that the start / end code is executed... And you don't want to force the code to be explicitly called through subclasses

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>