请高手帮忙:本人练习了一个oo的小例子,感觉有很多地方不足 请指点。
两个类, 这两个类中一个表示普通银行账户(简称 P) 一个表示金卡银行账户(简称 J)。 P为基类,J继承自P。J每次最多能取5000元,P一次最多3000元。J可以透支1万元,而P不能透支。两种账户均包括账面金额字段,存钱 取钱的方法。
用户测试两种账户的存钱 取钱功能。
class GeneralUser //普通用户类
{
//账面金额,因为要在子类中使用所以定义为保护类型
protected int accountNum = 0;
public GeneralUser()
{
}
//存钱方法,子类继承此方法,存钱和取钱的行为一样 所以用同一个方法就能解决问题,这应该没有问题吧?
public int InAccount(int inAccount)
{
this.accountNum+=inAccount;
return 0;
}
//取钱方法,因为P卡和J卡的取钱规则不同 所以在这定义一个虚方法,在子类中重写了该取钱方法
public virtual int OutAccount(int outAccount)
{
if(outAccount<=3000&&outAccount<=this.accountNum)
{
this.accountNum-=outAccount;
return 0;
}
else
{
Console.WriteLine("操作不符,请重来");
return -1;
}
}
//返回卡里余额的方法,子类继承次方法
public int Balance()
{
return accountNum;
}
}
//金卡用户类 继承普通卡用户类
class SuperUser : GeneralUser
{
public SuperUser(): base()
{
}
//金卡取钱方法 重写了基类的同名方法
public override int OutAccount(int money)
{
if(money<=5000)
{
if(this.accountNum+money<-10000)
return -2;
base.accountNum-=money;
return 0;
}
else
{
Console.WriteLine("操作不符,请重来");
return -1;
}
}
}
//取钱的方法
static int getMoney(GeneralUser user)
{
user.OutAccount(3000);
return 0;
}
static void Main(string[] args)
{
//实例化一个普通用户
GeneralUser g=new GeneralUser();
g.InAccount(1000);//存入1000元
getMoney(g);//取3000元,条件不符 报错
Console.WriteLine(g.Balance());//显示卡中的余额
g=new SuperUser();//实例化一个金卡用户
g.InAccount(2000);//存入2000
getMoney(g);//取出3000,由于金卡可以透支 所以 操作正常
Console.WriteLine(g.Balance());//显示卡内透支的金额
}
我感觉在用户取钱这个环节 还是有点别扭 但想不出来怎么解决,请高人予以答复。