I\'m confused because all I keep hearing is that private variables in Java are supposed to protect the code or the variable. But if anybody has access to the code, then it m
When programmers talk about accessing a variable, they mean accessing its value when the program runs. Protecting the code from changes is another matter entirely and requires human processes rather than syntax of a programming language. Making a variable private "protects" its value when the code runs. At this level, we are not concerned with protecting it from other programmers changing the code itself. The point of so-called "data hiding" is to keep internal data hidden from other classes which use the class. Those other classes should only access behavior by calling methods on the class, not by changing values of variables directly.
General programming principles such as "data hiding" are followed to help us as programmers write correct code. If any class can change a variable's value, then it is difficult to ensure that the value is valid. Say for example, you have a variable which counts the number of widgets a factory manufactures. By making the variable a private data member, you can more easily ensure that the value is never negative. On the other hand, if the variable is public, another class could change it to a negative value which can cause other parts of the code to crash.
Variables are private to protect the state of your objects - in object-oriented programming terms, this is called encapsulation.
Here's a very simple example. Imagine that we have a Person class, and a Person has an age that is calculated based on the year in which they were born.
class Person {
private int yearOfBirth;
private int age;
public Person(int yearOfBirth) {
this.yearOfBirth = yearOfBirth;
this.age = Calendar.getInstance().get(Calendar.YEAR) - yearOfBirth;
}
public int getAge() {
return age;
}
}
In another class somewhere, we have this... and if age was public, we could really mess up the state of our object by changing it without updating the year of birth.
public static void main(String[] args) {
Person bob = new Person(2000);
System.out.println("Bob's age: " + bob.getAge());
bob.age = 100; //This would be BAD!
}
By encapsulating the age variable, it's safe from unexpected changes and our class can manage its own state. Anyone who uses our class doesn't have to care about calculating a person's age, because that's encapsulated within our class.
why are variables private in java
To achieve encapsulation and this can't be accessible outside the class. This doesn't mean programmer can't change the source code.