java学习---面向对象三大特征--封装篇

package com.test_encapsulation;

public class encapsulation {
    public static void main(String[] args) {
        Person person = new Person();
        person.setName("jack");
        person.setAge(21);
        person.setSalary(800000);
        person.info();



    }
}
class Person{
    public String name;//名字公有
    private int age;//私密年龄
    private double salary;//薪水
//封装。
    public String getName() {
        return name;
    }

    public void setName(String name) {
        if (name.length()>=2&&name.length()<=6)//设置名字权限

        this.name = name;
        else
            System.out.println("名字过长!");
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        if (age>0&&age<200)//年龄权限
        this.age = age;
        else
            System.out.println("超出范围以设置,默认值18");
            this.age=18;
    }

    public double getSalary() {
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }
    public void info(){
        System.out.println(name+age+salary);
    }
}

package com.test_encapsulation;

public class encapsulation {
    public static void main(String[] args) {
        Person person = new Person("simt",20,80000);//构造器版本
        person.info();
//        person.setName("jack");
//        person.setAge(21);
//        person.setSalary(800000);
//        person.info();





    }
}
class Person{
    public String name;
    private int age;
    private double salary;
    public Person(String name,int age,double salary)
    {
        this.name=name;
        this.age=age;
        this.salary=salary;
        //为了使我们在封装写的条件有用,可以在构造器中调用他们
        setName(name);
        setAge(age);
        setSalary(salary);
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        if (name.length()>=2&&name.length()<=6)

        this.name = name;
        else
            System.out.println("名字过长!");
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        if (age>0&&age<200)
        this.age = age;
        else
            System.out.println("超出范围以设置,默认值18");
            this.age=18;
    }

    public double getSalary() {
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }
    public void info(){
        System.out.println(name+age+salary);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值