What is the advantage of having a private attribut

2019-04-06 05:24发布

This question already has an answer here:

In object oriented programming, I used to have this question and I still do :

What would be the benefit of declaring a class member as private if we will create for it a public getter and a public setter?

I don't see any difference at the security level between the case above and the case of declaring the class member as public.

Thanks!

标签: java c++ oop
15条回答
倾城 Initia
2楼-- · 2019-04-06 06:21

Accessor methods provide a single point of update for a given field. This is beneficial because validation logic or other modifications to the field can be controlled via the single method as opposed to having the field directly accessed throughout the code base.

See this IBM document which details more benefits: http://www.ibm.com/developerworks/java/library/ws-tip-why.html

查看更多
仙女界的扛把子
3楼-- · 2019-04-06 06:22

Actually, if you're developping alone on a small project and you won't reuse your code, it's kinda useless, but it's mostly a good habbit.

But, in team developpment, you may need to have some control on modification, and you can do it through the getters and setters.

Moreover, in some classes, you'll only have getters, as the setters will be done by the constructor, or via some other functions.

查看更多
疯言疯语
4楼-- · 2019-04-06 06:23

Quick (and a bit silly) example:

class Foo {

    private int age = -1;  // unset value

    public setAge(int a) {
        if (a < 0) {
            throw new IllegalArgumentException("Invalid age "+a);
        }
        age = a;
    }

    public getAge() {
       if (age < 0) {
           throw new InvalidStateException("Age was not previously set.")
       }
       return age;
    }    
}

In short: you gain control and you can assure values are correct. It's called encapsulation.

查看更多
登录 后发表回答