-
描述:创建一个名为
Account2_1
的类,模拟银行账户的基本操作。该类包含账号、户主名和余额等属性。提供三种构造方法,分别用于创建默认账户、带有账号和户主名的账户以及带有账号、户主名和初始余额的账户。实现存款和取款方法,其中存款金额必须大于0,取款时不允许透支。提供一个查询余额的方法和一个重写toString
方法以输出账户的详细信息。在Test2_1
类的main
方法中演示创建账户、存款、取款和查询余额的操作。
package shiyan2;
public class Account2_1 {
private String accountNumber; // 账号
private String ownerName; // 户主名
double balance; // 余额
// 构造方法(无参)
public Account2_1() {
this.accountNumber = "NewAccount";
this.ownerName = "Unknown";
this.balance = 0.0;
}
// 构造方法(带账号和户主名)
public Account2_1(String accountNumber, String ownerName) {
this.accountNumber = accountNumber;
this.ownerName = ownerName;
this.balance = 0.0;
}
// 构造方法(带账号、户主名和初始余额)
public Account2_1(String accountNumber, String ownerName, double initialBalance) {
this.accountNumber = accountNumber;
this.ownerName = ownerName;
this.balance = initialBalance;
}
// 存款方法
public void deposit(double amount) {
if (amount > 0) {
this.balance += amount;
System.out.println("存款成功,金额:" + amount + ",当前余额:" + this.balance);
} else {
System.out.println("存款金额必须大于0");
}
}
// 取款方法,不允许透支
public void withdraw(double amount) {
if (amount > 0 && this.balance >= amount) {
this.balance -= amount;
System.out.println("取款成功,金额:" + amount + ",当前余额:" + this.balance);
} else {
System.out.println("取款金额必须大于0,且不能透支");
}
}
// 查询余额方法
public double getBalance() {
return this.balance;
}
// 其他可能的方法,比如获取账号、户主名等
public String getAccountNumber() {
return this.accountNumber;
}
public String getOwnerName() {
return this.ownerName;
}
// 重写toString方法以便更好地输出账户信息
@Override
public String toString() {
return "{" +
"账号='" + accountNumber + '\'' +
", 户主名='" + ownerName + '\'' +
", 余额=" + balance +
'}';
}
}
package shiyan2;
public class Test2_1{
public static void main(String[] args) {
// 创建一个默认的新账户
Account2_1 account1 = new Account2_1();
System.out.println("账户1信息: " + account1);
// 存款到账户1
account1.deposit(1000.0);
// 创建一个带有初始信息的账户
Account2_1 account2 = new Account2_1("123456789", "张三", 500.0);
System.out.println("账户2信息: " + account2);
// 从账户2取款
account2.withdraw(200.0);
// 查询账户2的余额
System.out.println("账户2的余额: " + account2.getBalance());
// 尝试从账户2透支取款
account2.withdraw(500.0);
// 创建一个新的账户并直接设置余额
Account2_1 account3 = new Account2_1();
account3.balance = 800.0;
System.out.println("账户3信息: " + account3);
}
}