java封装案例练习

/创建程序,在其中定义2个类,AccountTest和Account类体会java的封装性
//1.Account要求具有属性;姓名(长度2-4),余额(必须大于20),密码(必须是6位数),如果不满足,则给出提示信息,并给默认值
//2.通过setxxx方法给Account的属性赋值
//3.在AccountTest中测试

public class AccountTest {
    public static void main(String[]args){
        Account text=new Account("马启航",123643568,"030120");
        Account text01=new Account("马启航gtdhdf",12,"0301206");

    }
}
//创建程序,在其中定义2个类,AccountTest和Account类体会java的封装性
//1.Account要求具有属性;姓名(长度2-4),余额(必须大于20),密码(必须是6位数),如果不满足,则给出提示信息,并给默认值
//2.通过setxxx方法给Account的属性赋值
//3.在AccountTest中测试

class Account{
     private String name;
     private double balance;//余额
     private String passwork;
     //创建构造器

    public Account(String name,double balance,String passwork){
        setName(name);
        setBalance(balance);
        setPasswork(passwork);
    }

    public String getPasswork() {
        return passwork;
    }

    public void setPasswork(String passwork) {
        if(passwork.length()==6){
            this.passwork = passwork;
        }else {
            System.out.println("请输入正确的密码,密码为6位数,否则密码为默认值");
            this.passwork="123456";
        }
    }

    public double getBalance() {
        return balance;
    }

    public void setBalance(double balance) {
        if (balance>20) {
            this.balance = balance;
        }else{
            System.out.println("余额必须大于20,否则余额为0");
            this.balance=0;
        }
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        if (name.length()>=2&&name.length()<=4){
            this.name = name;
        }else {
            System.out.println("请输入正确的名字,名字长度在2-4字符之间,否则名字变为匿名");
            this.name="匿名";
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值