Private variables or functions can only be used in the class in which they are declared.
Public variables or functions can be used throughout your application.
So, you must declare private all those variables and functions that you are going to use ONLY in the class in which they belong.
Example:
public class Car { private String model; public setModel(String model) { if (model != null) this.model = model; } public getModel() { return model; } private doSomething() { model = "Ford"; } }
In the Car class, we declare the String model private, because we will only use it in the Car class, by doing this we assure that other classes cannot change the value of this string without using the setModel function.
The setModel and getModel functions are publicly available, so we can access the private model variable from other classes ONLY using these methods.
In this example, the setModel function checks to see if the value is null, in which case it does not set the value. Here you can see that if you declared the String model publicly available, you would not have control over what value it writes.
The doSomething function is private, and other classes cannot use it. For the other hand, just like this function is private and belongs to the same class as the String model, it can change its value without using the setModel method.
source share