黑马程序员技术交流社区

标题: 成员变量私有化有什么作用? [打印本页]

作者: 蓦然回首3Y    时间: 2015-7-5 08:06
标题: 成员变量私有化有什么作用?
成员变量私有化有什么作用?
作者: Ruby    时间: 2015-7-5 09:18
封装的作用
作者: wgy    时间: 2015-7-5 10:16
成员变量私有化,一是为了体现面向对象的一种思想,即封装,二是向外界提供一种更加安全的访问方式,示例演示:测试类:
public class StudenTest {
        public static void main(String[] args) {
                Student s = new Student();
                s.setName("小明");
                s.setAge(14);
                System.out.println(s.getName()+"*****"+s.getAge());
        }
}
打印结果:
        小明*****14
学生类:
public class Student {
     //私有成员name
        private String name;
        //私有成员age
        private int age;
        //构造方法
        public Student() {
                super();
        }
        public String getName() {
                return name;
        }
        public void setName(String name) {
                this.name = name;
        }
        public int getAge() {
                return age;
        }
        public Student(String name, int age) {
                super();
                this.name = name;
                this.age = age;
        }
        public void setAge(int age) {
                this.age = age;
        }
}



作者: zhjunwenyy    时间: 2015-7-5 14:34
封装,不对外暴露
作者: qq4916097    时间: 2015-7-5 16:15
私有化后的成员就不能被外界访问了。比如说你老婆和你领了结婚证(私有化),这样别人就不能和她再领一次结婚证了(不被外界访问)
作者: fmi110    时间: 2015-7-5 16:23
就是属于自己的 被人不能随意碰,具体实际含义我也还没理解
作者: 蓦然回首3Y    时间: 2015-7-5 17:52
明白了。。。。。。。。。。。。。
作者: pathnet    时间: 2015-7-5 20:35
保护字段的安全性
作者: 942932576    时间: 2015-7-5 22:30
可以对不想让别人访问的数据进行保护,私有化后只能本类才能访问
作者: hejin67410    时间: 2015-9-21 20:32
谢谢分享




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2