/*
* 创建程序,在其中定义两个类: Account 和AccountTest类体会Java的封装性。
* Account类要求具有属性:
* 姓名(长度为2位3位或4位)
* 余额(必须>20)
* 密码(必须是六位)
* 如果不满足,则给出提示信息,并给默认值,
* 通过setXxx的方法给Account的属性赋值。
* 在AccountTest中测试。
*/
public class Account {
private String name;
private double balance; //balance 余额
private String pwd;
public Account() {
}
public Account(String name, double balance, String pwd) {
this.setName(name);
this.setBalance(balance);
this.setPwd(pwd);
}
public String getName() {
return name;
}
//姓名(长度为2位3位或4位)
public void setName(String name) {
if(name.length() >= 2 && name.length() <= 4){
this.name = name;
}else {
System.out.println("输入错误!姓名2-4位,默认为xxx");
this.name = "xxx";
}
}
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 getPwd() {
return pwd;
}
public void setPwd(String pwd) {
if (pwd.length() == 6) {
this.pwd = pwd;
}else {
System.out.println("输入错误!密码(必须是六位),默认为123456");
this.pwd = "123456";
}
}
public void showInfo(){
System.out.println("姓名: " + name + " 余额: " + balance + " 密码: " + pwd);
}
}
public class AccountTest {
public static void main(String[] args) {
Account account1 = new Account();
account1.setName("张三");
account1.setBalance(200);
account1.setPwd("123456");
account1.showInfo();
System.out.println("===========================================");
Account account2 = new Account();
account2.setName("张");
account2.setBalance(19.5);
account2.setPwd("12345");
account2.showInfo();
}
}
封装的练习
最新推荐文章于 2024-09-16 21:37:07 发布