Why do we declare Private variables in Java

2020-03-30 05:09发布

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 makes no difference if it is private, they can still change it. So how is it considered protected when anybody who has access to the code can change it.

7条回答
狗以群分
2楼-- · 2020-03-30 05:53

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.

查看更多
登录 后发表回答