封装入门小案例

需求:

1.FengZhuang.test1 包:AccountTest.java 和 Account.java

2.创建程序,在其中定义两个类:AccountTest.java 和 Account.java。

3.Account类要求具有属性:姓名(长度为[2-4])、余额(>20)、密码(必须是六位)、如果不满足就给       出提示信息,并给出提示信息(自己定义)。

4.通过setXxxx的方法给 Account 的属性赋值。

5.在 AccountTest 中进行测试。

6. 可以分别创建一个(无参数的构造器)和 一个 (有参数的构造器)。

实现:

1.Account类

package FengZhuang.test1;
 
public class Account {
    //定义的三个私有属性
    private String name;
    private double balance;
    private String pass;
    //无参构造器
    public Account() {
    }
    //有参构造器
    public Account(String name, double balance, String pass) {
        this.setName(name);
        this.setBalance(balance);
        this.setPass(pass);
    }
    // name 赋值方法
    public void setName(String name) {
        // 判断语句
        if(name.length() >=2 && name.length() <=4){
            this.name = name;
        }else {
            System.out.println("名字范围[2-4],给你一个默认值无名氏");
            this.name = "无名氏";
        }
    }
    // balance 赋值方法
    public void setBalance(double balance) {
        // 判断语句
        if(balance > 20){
            this.balance = balance;
        }else {
            System.out.println("你的余额不大于20,不显示了");
        }
    }
    // pass 赋值方法
    public void setPass(String pass) {
        // 判断语句
        if(pass.length() ==6){
            this.pass = pass;
        }else {
            System.out.println("密码必须是6位,分配默认密码:123456");
            this.pass = "123456";
        }
    }
    //将属性信息输出
    public String info(){
        return "信息:"+"name="+this.name+" balance="+this.balance+" pass="+this.pass;
    }
}

2.AccountTest类

package FengZhuang.test1;
 
public class AccountTest {
        public static void main(String[] args) {
            System.out.println("====jack的信息====");
            //无参构造器
            Account account = new Account();
            account.setName("jack");
            account.setBalance(8900);
            account.setPass("777888");
            System.out.println(account.info());
            System.out.println("====smi的信息====");
            //有参构造器
            Account smi = new Account("smi", 6000, "666666");
            System.out.println(smith.info());
        }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值