使用getter和setter具有私有属性的优点是什么? [英] What is the advantage of having a private attribute with getters and setters?

查看:390
本文介绍了使用getter和setter具有私有属性的优点是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在面向对象编程中,我曾经有这个问题,我仍然这样做:

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


声明类的好处是什么成员为私人(如果我们
将为其创建公共获取者公开设置者)?

在上述情况和将类成员声明为public之间的安全级别上,我没有看到任何差异。

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

感谢!

推荐答案

封装提供了数据隐藏和更多控制成员变量。如果一个属性是公共的,任何人都可以访问它,并可以为它分配任何值。但如果你的成员变量是私有的,你已经提供了一个setter。

Encapsulation provides data hiding and more control on the member variables. If an attribute is public then anyone can access it and can assign any value to it. But if your member variable is private and you have provided a setter for it. Then you always have an option to put some constraints check in the setter method to avoid setting an illogical value.

例如,只有public成员的类:

For example a class with public member only :

class MyClass {
    public int age;
}

public MyClassUser {

    public static void main(String args[]) {
        MyClass obj = new MyClass();
        obj.age = -5 // not a logical value for age
    }
}

与私有成员和设置者具有相同的类:

Same class with private member and a setter:

 class MyClass {
     private int age;
     public void setAge(int age) {
         if(age < 0) {
            // do not use input value and use default
         } else { 
            this.age = age;
         }
     }
 }

这篇关于使用getter和setter具有私有属性的优点是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆