[oop] Private vs Protected - Visibility Good-Practice Concern

I've been searching and I know the theoretic difference.

  • public - Any class/function may access the method/property.
  • protected - Only this class and any subclasses may access the method/property.
  • private - Only this class may access the method/property. It won't even be inherited.

That's all fine and well, the question is, what's the practical difference between them? When would you use private and when would you use protected? Is there a standard or acceptable good practice over this one?

Up until now, to retain the concept of inheritance and polymorphism, I use public for anything that should be accessed from the outside (like constructors and main class functionality), and protected for internal methods (logic, helper methods etc). Am I on the right track?

(Note that this question is for me, but also for future reference as I haven't seen a question like this one SO).

This question is related to oop language-agnostic coding-style

The answer is


Well it is all about encapsulation if the paybill classes handles billing of payment then in product class why would it needs the whole process of billing process i.e payment method how to pay where to pay .. so only letting what are used for other classes and objects nothing more than that public for those where other classes would use too, protected for those limit only for extending classes. As you are madara uchiha the private is like "limboo" you can see it (you class only single class).


I read an article a while ago that talked about locking down every class as much as possible. Make everything final and private unless you have an immediate need to expose some data or functionality to the outside world. It's always easy to expand the scope to be more permissible later on, but not the other way around. First consider making as many things as possible final which will make choosing between private and protected much easier.

  1. Make all classes final unless you need to subclass them right away.
  2. Make all methods final unless you need to subclass and override them right away.
  3. Make all method parameters final unless you need to change them within the body of the method, which is kinda awkward most of the times anyways.

Now if you're left with a final class, then make everything private unless something is absolutely needed by the world - make that public.

If you're left with a class that does have subclass(es), then carefully examine every property and method. First consider if you even want to expose that property/method to subclasses. If you do, then consider whether a subclass can wreak havoc on your object if it messed up the property value or method implementation in the process of overriding. If it's possible, and you want to protect your class' property/method even from subclasses (sounds ironic, I know), then make it private. Otherwise make it protected.

Disclaimer: I don't program much in Java :)


Stop abusing private fields!!!

The comments here seem to be overwhelmingly supportive towards using private fields. Well, then I have something different to say.

Are private fields good in principle? Yes. But saying that a golden rule is make everything private when you're not sure is definitely wrong! You won't see the problem until you run into one. In my opinion, you should mark fields as protected if you're not sure.

There are two cases you want to extend a class:

  • You want to add extra functionality to a base class
  • You want to modify existing class that's outside the current package (in some libraries perhaps)

There's nothing wrong with private fields in the first case. The fact that people are abusing private fields makes it so frustrating when you find out you can't modify shit.

Consider a simple library that models cars:

class Car {
    private screw;
    public assembleCar() {
       screw.install();
    };
    private putScrewsTogether() {
       ...
    };
}

The library author thought: there's no reason the users of my library need to access the implementation detail of assembleCar() right? Let's mark screw as private.

Well, the author is wrong. If you want to modify only the assembleCar() method without copying the whole class into your package, you're out of luck. You have to rewrite your own screw field. Let's say this car uses a dozen of screws, and each of them involves some untrivial initialization code in different private methods, and these screws are all marked private. At this point, it starts to suck.

Yes, you can argue with me that well the library author could have written better code so there's nothing wrong with private fields. I'm not arguing that private field is a problem with OOP. It is a problem when people are using them.

The moral of the story is, if you're writing a library, you never know if your users want to access a particular field. If you're unsure, mark it protected so everyone would be happier later. At least don't abuse private field.

I very much support Nick's answer.


Let me preface this by saying I'm talking primarily about method access here, and to a slightly lesser extent, marking classes final, not member access.

The old wisdom

"mark it private unless you have a good reason not to"

made sense in days when it was written, before open source dominated the developer library space and VCS/dependency mgmt. became hyper collaborative thanks to Github, Maven, etc. Back then there was also money to be made by constraining the way(s) in which a library could be utilized. I spent probably the first 8 or 9 years of my career strictly adhering to this "best practice".

Today, I believe it to be bad advice. Sometimes there's a reasonable argument to mark a method private, or a class final but it's exceedingly rare, and even then it's probably not improving anything.

Have you ever:

  • Been disappointed, surprised or hurt by a library etc. that had a bug that could have been fixed with inheritance and few lines of code, but due to private / final methods and classes were forced to wait for an official patch that might never come? I have.
  • Wanted to use a library for a slightly different use case than was imagined by the authors but were unable to do so because of private / final methods and classes? I have.
  • Been disappointed, surprised or hurt by a library etc. that was overly permissive in it's extensibility? I have not.

These are the three biggest rationalizations I've heard for marking methods private by default:

Rationalization #1: It's unsafe and there's no reason to override a specific method

I can't count the number of times I've been wrong about whether or not there will ever be a need to override a specific method I've written. Having worked on several popular open source libs, I learned the hard way the true cost of marking things private. It often eliminates the only practical solution to unforseen problems or use cases. Conversely, I've never in 16+ years of professional development regretted marking a method protected instead of private for reasons related to API safety. When a developer chooses to extend a class and override a method, they are consciously saying "I know what I'm doing." and for the sake of productivity that should be enough. period. If it's dangerous, note it in the class/method Javadocs, don't just blindly slam the door shut.

Marking methods protected by default is a mitigation for one of the major issues in modern SW development: failure of imagination.

Rationalization #2: It keeps the public API / Javadocs clean

This one is more reasonable, and depending on the target audience it might even be the right thing to do, but it's worth considering what the cost of keeping the API "clean" actually is: extensibility. For the reasons mentioned above, it probably makes more sense to mark things protected by default just in case.

Rationalization #3: My software is commercial and I need to restrict it's use.

This is reasonable too, but as a consumer I'd go with the less restrictive competitor (assuming no significant quality differences exist) every time.

Never say never

I'm not saying never mark methods private. I'm saying the better rule of thumb is to "make methods protected unless there's a good reason not to".

This advice is best suited for those working on libraries or larger scale projects that have been broken into modules. For smaller or more monolithic projects it doesn't tend to matter as much since you control all the code anyway and it's easy to change the access level of your code if/when you need it. Even then though, I'd still give the same advice :-)


When would you use private and when would you use protected?

Private Inheritance can be thought of Implemented in terms of relationship rather than a IS-A relationship. Simply put, the external interface of the inheriting class has no (visible) relationship to the inherited class, It uses the private inheritance only to implement a similar functionality which the Base class provides.

Unlike, Private Inheritance, Protected inheritance is a restricted form of Inheritance,wherein the deriving class IS-A kind of the Base class and it wants to restrict the access of the derived members only to the derived class.


Examples related to oop

How to implement a simple scenario the OO way When to use 'raise NotImplementedError'? PHP: cannot declare class because the name is already in use Python class input argument Call an overridden method from super class in typescript Typescript: How to extend two classes? What's the difference between abstraction and encapsulation? An object reference is required to access a non-static member Java Multiple Inheritance Why not inherit from List<T>?

Examples related to language-agnostic

IOException: The process cannot access the file 'file path' because it is being used by another process Peak signal detection in realtime timeseries data Match linebreaks - \n or \r\n? Simple way to understand Encapsulation and Abstraction How can I pair socks from a pile efficiently? How do I determine whether my calculation of pi is accurate? What is ADT? (Abstract Data Type) How to explain callbacks in plain english? How are they different from calling one function from another function? Ukkonen's suffix tree algorithm in plain English Private vs Protected - Visibility Good-Practice Concern

Examples related to coding-style

Method Call Chaining; returning a pointer vs a reference? 80-characters / right margin line in Sublime Text 3 Cannot find reference 'xxx' in __init__.py - Python / Pycharm How to stick <footer> element at the bottom of the page (HTML5 and CSS3)? Simple way to create matrix of random numbers Is calling destructor manually always a sign of bad design? Count all values in a matrix greater than a value Iterate through a C++ Vector using a 'for' loop Which comment style should I use in batch files? Dictionaries and default values