当前位置: 首页 > article >正文

面向对象编程的三大特征之一-封装

实现封装的步骤

1、将属性是私有化的 不能直接修改属性

2、提供一个公共的set方法,用与对属性判断并赋值

3、提供一个公共的get方法,用于获取属性的值

public class Encap_ {
    public static void main(String[] args) {
        Person person = new Person();
        person.setName("jack");
        person.setAge(90);
        person.setSalary(300000.0);
        person.setJob("销售经理");
        System.out.println(person.info());
        System.out.println("构造器使用");
        Person p = new Person("smith", 100, 30000.0, "部长");
        System.out.println(p.info());
    }
}
class Person {
    public String name;
    private int age;
    private double salary;
    private String job;
    // 无参构造器
    public Person() {
    }

    public Person(String name, int age, double salary, String job) {
    // this.name = name;
    // this.age = age;
    // this.salary = salary;        
    // 将构造器与setXXX结合使用
        this.setName(name);
        this.setAge(age);
        this.setSalary(salary);
        this.setJob(job);
    }

    //快捷键 Alt + Insert 选择 getter and setter
    public void setName(String name) {
        //判断name的长度
        // name的长度在2-6之间
        if (name.length() >= 2 && name.length() <= 6) {
            this.name = name;
        } else {
            System.out.println("名字的长度应在2-6之间");
        }
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        // 判断年龄是否在1-120之间
        // 并对设置的年龄进行合理的验证,年龄合理就设置 否则就默认
        if (age >= 1 && age <= 120) {
            this.age = age;
        } else {
            this.age = 18;
        }
    }

    public double getSalary() {
        // 可以增加对当前对象的权限判断
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }

    public String getJob() {
        return job;
    }

    public void setJob(String job) {
        this.job = job;
    }

    // 创建一个方法打印信息
    public String info() {
        return "name=" + name + "\tage=" + age + "\tsalary=" + salary + "\tjob=" + job;
    }
}


http://www.kler.cn/a/227156.html

相关文章:

  • HDMI2.1之eARC简介-Dolby Atmos和DTS:X
  • Ai时代掘金的思考
  • MySQL原理(五)事务
  • centos7安装oracle
  • Android进阶之路 - 通过业务(Activity)栈管理业务流程
  • clr的执行模型-笔记
  • 微信小程序 app.js 简单调用其他页面的方法
  • 【python】类似FileZilla Client的程序
  • 嵌入式学习第十六天!(Linux文件查看、查找命令、标准IO)
  • 【Nginx】nginx入门
  • 学习使用Flask模拟接口进行测试
  • H5 自适应超人背景引导页源码
  • FollowYourPose 安装踩坑
  • 【C++】C++入门— 类与对象初步介绍
  • 数据库-计算机三级学习记录-4DBAS功能概要设计
  • 浙政钉(专有钉钉)
  • 重写Sylar基于协程的服务器(4、协程调度模块的设计)
  • moment.js 常用方法使用
  • 【数据分享】1929-2023年全球站点的逐月降雪深度数据(Shp\Excel\免费获取)
  • 从源代码看Chrome 版本号