我的账户
啄木鸟学院

专注软件测试菁英教育

亲爱的游客,欢迎!

已有账号,请

如尚未注册?

JAVA-张荣亮-2021.03.10

[复制链接]
张荣亮 发表于 2021-3-10 19:57:30 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题
package day04;

/*
封装:属性设置为private的,封装在类的内部,对外提供publicget/set方法供外部调用。
        在类内部对参数做一些限制,防止非法的调用。
*/

public class Demo01 {
    public static void main(String[] args) {
        Student s1 = new Student("zhangsan", 18, 90);
        System.out.println(s1);
        // 在类的外部可以访问到属性。
        s1.name = "张三"; // 设置/获取属性,实例。属性名。
        s1.score = 99; // 0~150
        System.out.println(s1);
        // 设置的分数不合理,也能设置
        s1.score = -500;
        System.out.println(s1);

        Student1 s2 = new Student1("lisi", 18, 90);
        System.out.println(s2);
        // s2.name = "李四"; // 私有的属性在外部无法访问
        // s2.score = 99;
        s2.setScore(100);
        System.out.println(s2.getScore());
        s2.setAge(30);
        System.out.println(s2.getAge());
    }
}

// 未封装的
class Student {
    String name;
    int age;
    float score;

    public Student(String name, int age, float score) {
        this.name = name;
        this.age = age;
        this.score = score;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", score=" + score +
                '}';
    }
}
// 封装后的
class Student1 {
    private String name;
    private int age; // 3~30
    private float score;


    public int getAge() {
        return age;
    }

    public void setAge(int a) {
        if (a<3 || a>30) {
            System.out.println("参数错误");
        } else {
            age = a;
        }
    }

    // 获取属性的值
    public float getScore() {
        return score;
    }
    // 设置属性的值
    public void setScore(float s) {
        if (s < 0 || s > 150) {
            System.out.println("参数不合法");
        } else {
            score = s;
        }
    }

    public Student1(String name, int age, float score) {
        this.name = name;
        this.age = age;
        this.score = score;
    }

    @Override
    public String toString() {
        return "Student1{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", score=" + score +
                '}';

    }
}

class Student2 {
    private String name;
    private int age;
    private float score;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public float getScore() {
        return score;
    }

    public void setScore(float score) {
        this.score = score;
    }
}

回复

使用道具 举报

关注0

粉丝0

帖子20

发布主题
大家都在学
课堂讨论
一周热帖排行最近7x24小时热帖
关注我们
专注软件测试菁英教育

客服电话:17792550360

客服时间:9:00-21:00

卓目鸟学苑 - 专注软件测试菁英教育!( 陕ICP备2025058934号-2 )

版权所有 © 西安菁英教育科技有限公司 2023-2026