首页 > 其他分享 >面向对象08:封装详解

面向对象08:封装详解

时间:2024-03-25 23:55:23浏览次数:32  
标签:封装 name 08 private sex 面向对象 age public s1

package com.oop.demo04;

//类   private:私有
public class Student {
    //属性私有,封装大多数时候都是对于属性来的
    private String name;//名字,以前public所有人都可以操作这个名字,现在属性私有就不让所有人都可以操纵这个属性了
    private int id;//学号
    private char sex;//性别
    private int age;

    //提供一些可以操作这个属性的方法!
    //提供一些public的get、set方法

    //get获得这个数据
    public String getName(){
        return this.name;
    }

    //set 给这个数据设置值
    public void setName(String name){
        this.name = name;
    }

    //alt+insert,选中属性可以自动给属性设置get和set方法

    public char getSex() {
        return sex;
    }

    public void setSex(char sex) {
        this.sex = sex;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        if(age>120 || age<0){
            this.age = age;
        }else{
            age=3;//安全性检查
        }

    }
}
package com.oop;

import com.oop.demo04.Student;

/*
* 封装的意义
* 1.提高程序的安全性
* 2.隐藏代码的实现细节
* 3.统一接口
* 4.系统的可维护性增加了
* */
public class Application {
    public static void main(String[] args) {
        Student s1 = new Student();
        s1.setName("qingjiang");
        System.out.println(s1.getName());


        s1.setAge(999);//把年龄设置成这样是不合法的,所以需要在封装时做一些安全性检查
        System.out.println(s1.getAge());

    }
}

 

标签:封装,name,08,private,sex,面向对象,age,public,s1
From: https://www.cnblogs.com/sankouyitouju/p/18095689

相关文章