Java三大特性之一(封装)

封装

  • 程序设计一般要求:“高内聚,低耦合”。高内聚就是类的内部数据操作细节自己完成,不允许外部干涉;低耦合:仅暴露少量的方法给外部使用。

  • 封装(数据的隐藏)

    • 通常,应禁止直接访问一个对象中数据的实际表示,而应通过操作接口来访问,这称为信息的隐藏。

  • 记住一句话:属性私有,get/set

//属性私有,get/set
​
package com.oop.Demo3;
//Student类
public class Student {
    //属性私有  使用private
    private String name;  //姓名
    private int id;       //学号
    private int age;      //年龄
    private char sex;     //性别
    /*
    提供一些可以操作这些属性的方法
    提供一些public的get或者set的方法
     */
    //get或者set
​
    //Alt键+Insert键 可以快速生成set和get方法
    //get 获取属性变量名
    //set 给属性变量名设置值
    
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
​
    public int getId() {
        return id;
    }
​
    public void setId(int id) {
        this.id = id;
    }
​
    public int getAge() {
        return age;
    }
​
    public char getSex() {
        return sex;
    }
​
    public void setSex(char sex) {
        this.sex = sex;
    }
​
    public void setAge(int age) {
        if(age>150 || age <0){
            this.age = 3;
        }else {
            this.age = age;
        }
​
    }
​
​
}
​

封装的作用

/*封装的作用
1、提高程序的安全性,保护数据
2、隐藏代码的实现细节
3、统一接口
4、提高了程序的可维护性
 */
package com.oop;
import com.oop.Demo3.Student;
/*封装的作用
1、提高程序的安全性,保护数据
2、隐藏代码的实现细节
3、统一接口
4、提高了程序的可维护性
 */
​
​
public class Application {
    public static void main(String[] args) {
        Student s1 = new Student();
        s1.setName("陈彬彬");
        s1.setId(666);
        s1.setAge(29);
        s1.setSex('男');
​
        String name = s1.getName();
        int id = s1.getId();
        char sex = s1.getSex();
        int age = s1.getAge();
        Class<? extends Student> s1Class = s1.getClass();
        System.out.println("姓名:"+name);
        System.out.println("学号:"+id);
        System.out.println("性别:"+sex);
        System.out.println("年龄:"+age);
        System.out.println("类名:"+s1Class);
    }
}
​

猜你喜欢

转载自blog.csdn.net/weixin_40294256/article/details/117322558
今日推荐