I understand it is a very basic concept in the oops. But still I cannot get my head around. I understood why member variables are private, so class user cannot abuse it by setting up invalid values.
But how can this apply to the methods ?
I understand it is a very basic concept in the oops. But still I cannot get my head around. I understood why member variables are private, so class user cannot abuse it by setting up invalid values.
But how can this apply to the methods ?
Private methods are useful for breaking tasks up into smaller parts, or for preventing duplication of code which is needed often by other methods in a class, but should not be called outside of that class.
Having all other answers in mind. It is worth to remember that private method are only a tip for a programmer in many languages. In most cases it is still possible to use private method. For example by creating an object that inherits from object with private method and overrides its method with new public method.
In some modern highly object oriented languages private methods exist only by convention. Method with '_' on beginning is considere to be private.
Well in some cases you want only that specific class to use a method, and protect it from being used by any other class.
Just an example to show how it can be used:
You have a class Clock, it runs and runs keeping track of the time and date. You can get the time or date from it trough public methods. But the clock has to be right. so you can't adjust the time or date from outside of the class. But the clock itself needs to be able to adjust the time (daylights saving time for example)
In this case the Clock will have a private method to adjust the time.
Then you also have an additional pro, which is structuring the code. You can split up your code in smaller private methods which structure the code but prevent them from being used outside your class.
Methods are (also) used to structure code, and I don't want the internal structure of my implementation to leak out through the interface. Often I have a method which to the outside seems to do a single task, but actually has to perform a couple of smaller tasks. In such cases I make one small private method for each of the subtasks and call them from the publicly visible method.
Methods that are private can only be called by methods within the same class or within the same "module". Methods are not commonly made private; usually they're made protected so that children can call them, or public so that other code can call them.
For exactly the same reason - some methods are only intended for use inside the class, and use by non-class objects would be abuse. Think of methods that increment and decrement an object count for the class - these should only be called from a class's constructors or destructor, and so should be private.