一、实验目的
通过让学生独立实现客户从银行账户存取钱的操作,使学生能够掌握面向对象编程的思想及方法。
(1)理解面向对象编程思想
(2)掌握类和对象的创建方法
(3)掌握构造方法以及实例方法的定义和调用
(4) 掌握封装的应用
二、实验内容和要求
题目要求:完成如下程序,代码行必须加注释。(记录所有过程和步骤,有截图,有说明。页数可增加)
(1)编写一个名为Account类的模拟账户。该类包含的属性有:账户id, 余额balance,年利率annualInterestRate。该类包含的方法有:取款方法withdraw( ), 存款方法deposit( )。
编写一个Customer类,并实现相应的属性和方法。
(2)编写一个测试程序:创建一个Customer对象,名字叫做HelloKitty, 她有一个账号为1000, 余额为2000, 年利率为1. 23% 。她进行了如下操作:存入100元,再取出900元,再取出2000元。2
(3)要求通过测试程序打印输出:
成功存入:100.0元
成功取出:900.0元
余额不足,取钱失败!
public class Account {
//定义属性
protected int id;
protected int balance;
protected double annualInterestRate;
//构造方法
public Account(int id,int balance,double annualInterestRate) {
this.id=id;
this.balance=balance;
this.annualInterestRate=annualInterestRate;
}
//get,set方法
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getBalance() {
return balance;
}
public void setBalance(int balance) {
this.balance = balance;
}
public double getAnnualInterestRate() {
return annualInterestRate;
}
public void setAnnualInterestRate(double annualInterestRate) {
this.annualInterestRate = annualInterestRate;
}
//取款
public void withdraw(int a) {
if(a>balance) {
System.out .print("余额不足,取钱失败");
}else {
balance=balance-a;
System.out .println("成功取出"+a+"元");}
}
//存款
public void deposit(int b) {
balance=balance+b;
System.out .println("存入"+b+"元");
}
}
//Customer类继承Account类
public class Customer extends Account {
//定义名字
private String name;
//构造方法
public Customer(int id,int balance,double annualInterestRate,String name) {
super(id,balance,annualInterestRate); //调用父类的属性
this.name=name;
}
public String getName() {
return name;
}
}
public class Main {
public static void main(String[] args) {
//实例化对象
Customer p =new Customer(1000,2000,0.0123,"HelloKitty");
System.out.println(p.getId());
System.out.println(p.getBalance());
System.out.println(p.getAnnualInterestRate());
System.out.println(p.getName());
p.withdraw(900); //取款900
p.deposit(100); //存进100
p.withdraw(2000); //取款2000
}
}