java 面向对象demo练习
时间:2025-4-1 17:20 作者:杨佳乐 分类: Java
public class Demo3Test1 {
// oop练习 使用面向对象实现一个简单的银行账户系统
public static void main(String[] args) {
BankAccount bank1 = new BankAccount("100001","张三",0);
bank1.displayInfo();
// 存款
bank1.deposit(100);
// 取款
bank1.withdraw(10);
bank1.withdraw(10000);
bank1.displayInfo();
}
}
class BankAccount{
private String accountNumber; // 账号
private String owner; // 姓名
private double balance; // 余额
// 构造方法
public BankAccount(String accountNumber,String owner,double balance){
this.accountNumber = accountNumber;
this.owner = owner;
this.balance = balance;
}
// 存款方法
public void deposit(double num){
this.balance = this.balance + num;
}
// 取款方法
public void withdraw(double num){
if(this.balance < num){
System.out.println("余额不足");
return;
}
this.balance = this.balance - num;
}
// 打印用户信息
public void displayInfo(){
System.out.println("账号:"+this.accountNumber+",持有人:"+this.owner+",余额:"+this.balance);
}
}