本文中为了更好的演示类、构造方法的引用,我们将一个实例分别写在两个class中,分别为 Account和PersonAccount中,其中后者包含各种方法、构造方法;前者进行调用输出。此实例模拟了银行系统的查询、修改密码、取款存款等简单操作,具体代码如下:
public class PersonAccount {
private String name;
private String id;
private int pwd;
private double balance;
public PersonAccount( String name,String id,int pwd,double balance){
this.name=name;
this.id=id;
this.pwd=pwd;
this.balance=balance;
}
public String getName(){
return name;
}
public String getID(){
return id;
}
public double getBalance(){
return balance;
}
public double changePwd(int newPwd){
pwd=newPwd;
return pwd;
}
public double cunkuan(double setMoney){
balance=balance+setMoney;
return balance;
}
public double qukuan(double getMoney){
if(getMoney>balance){
System.out.println("余额不足");
}else{
balance=balance-getMoney;
} return balance;
}
}
import java.util.Scanner;
public class Account {
public static void main(String[] args) {
PersonAccount p1=new PersonAccount("王晨", "123421413413", 123456, 20000);
System.out.println("该账户的所有人为"+p1.getName());//显示账户名称
System.out.println("该账户的ID为"+p1.getID());//查询ID
System.out.println("该账户的余额为"+p1.getBalance());//查询余额
System.out.println("请输入新的密码");
Scanner p=new Scanner(System.in);//修改密码
int pwd1=p.nextInt();
System.out.println("请再次输入新的密码");//修改密码确认
Scanner p2=new Scanner(System.in);
int pwd2=p.nextInt();
if(pwd1==pwd2){
p1.changePwd(pwd1);
System.out.println("该账户新密码修改成功");
}else{
System.out.println("两次输出不一致,修改失败");
}
System.out.println("请输入取钱金额");
double getMoney=p.nextDouble();//取钱[
System.out.println("取钱后账户余额"+p1.qukuan(getMoney));
System.out.println("请输入存钱金额");
double setMoney=p.nextDouble();//存钱
System.out.println("存钱后账户余额"+p1.cunkuan(setMoney));
}
}