在这里先介绍下如何取消自动分配形参
java-封装课堂练习
Accountl类源码
package com.Test;
public class Account {
//为了封装 将3个属性设置为private
private String name;
private double 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位3位或4位),默认无名");
this.name = "无名";
}
}
public double getBalance() {
return balance;
}
//余额(必须>20)
public void setBalance(double balance) {
if (balance > 20) {
this.balance = balance;
} else {
System.out.println("余额(必须>20) 默认为0");
}
}
public String getPwd() {
return pwd;
}
//密码(必须是6位数)
public void setPwd(String pwd) {
if (pwd.length() == 6) {
this.pwd = pwd;
} else {
System.out.println("密码(必须是6位数)默认密码000000");
this.pwd = "000000";
}
}
//设置一个方法显示账号信息
public void showInfo() {
//这里也可以自己设置一下增加权限的效验
System.out.println("账号信息 名字=" + name + "\t" +
"余额=" + balance + "\t" + "密码=" + pwd);
}
}
TestAccount测试类源码
package com.Test;
public class TestAccount {//在TestAccount类里面测试
public static void main(String[] args) {
//创建Account
Account account = new Account();
account.setName(“jack12t”);
account.setBalance(5);
account.setPwd(“00000015”);
account.showInfo();
}
}