海阔天空

当前时间为:
欢迎大家来到海阔天空https://www.9713job.com,广告合作以及淘宝商家推广请微信联系15357240395

2020java教程:面向对象的三大特性之封装

未分类
2020-08-09 15:05:45
1822677238@qq.com

手机扫码查看

2020java教程:面向对象的三大特性之封装

面向对象的三大特性之封装

封装的必要性

public class demos{
    public static void main(String[] args) {
        Student s1=new Student();
        s1.name="tom";
        s1.age=20000;//在对象的外部,为对象的属性赋值
        // 可能存在非法数据的录入
        //现阶段没有办法对属性的赋值加以控制
        //使用封装可以解决数据的非法问题
        s1.sex="male";
    }
}
class Student{
    String name;
    int age;
    String sex;
}

什么的封装?
概念:尽可能隐藏对象的内部实现细节,控制对象的修改及访问的权限
访问修饰符:private (可将属性修饰为私有,仅本类可见)

public class demos{
    public static void main(String[] args) {
        Student s1=new Student();
        s1.name="tom";
        //s1.age=20000;//编译错误,私有属性在类的外边不可访问
        s1.sex="male";
        s1.sayHi();//通过sayHi方法间接访问age属性
    }
}
class Student{
    String name;
    private int age;//私有属性(本类可见)
    String sex;
    public void sayHi(){//只能取值不能赋值,也不行
        System.out.println("年龄为"+this.age);
    }
}

公共访问方法
public class demos{
    public static void main(String[] args) {
        Student s1=new Student();
        s1.name="tom";
        int age=20000;
        s1.setAge(age);//赋值
        //取值
        System.out.println("年龄为"+s1.getAge());
    }
}
class Student{
    String name;
    private int age;//私有属性(本类可见)
    //提供公共访问方法,以保证数据的正常录入
    //命名规范:
    // 赋值:set属性名()
    public void setAge(int age) {
        //设置过滤器筛选非法值
        if(age>0&&age<=100) {
            this.age = age;//局部变量赋值给成员变量
        }else this.age=18;//设置默认值18岁
    }
    //取值 get属性名()
    public int getAge() {
        return this.age;
    }
}

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注