创建一个银行账户Account 类,有存款,取款等方法,在创建两个子类,其中有一个是SavingAccount,SavingAccount不能透支,所以能否使SavingAccount不访问取款方法?
代码如下(没写完):package pkg;public class test9_3 {
public void main(String[] args)
{
// SavingAcc saving = new SavingAcc();
}
public class Account
{
int accountNum= 0;
private double balance = 0;//yu e
private double yearInterest = 0;
private String openDate = null ;
Account(int accountNum , double balance , double yearInterest ,String openDate)
{
this.accountNum = accountNum;
this.balance = balance ;
this.yearInterest = yearInterest ;
this.openDate = openDate ;
System.out.print("this is Account class");
}
// Account(){}
public double getBanlance()
{
return balance;
}
public void deposit(double depositMoney)
{
balance += depositMoney ;
}
public void drawMoney(double DMoney)
{
balance -=DMoney;
}
}
}
package pkg;import pkg.test9_3.Account;public class SavingAcc extends Account { SavingAcc(test9_3 test9_3, int accountNum, double balance,double yearInterest, String openDate) {
test9_3.super(accountNum, balance, yearInterest, openDate);
// TODO Auto-generated constructor stub
if(this.getBanlance() < 0)
{
System.out.println("your Account's balance is lower than $0");
}
else
;
}
}
代码如下(没写完):package pkg;public class test9_3 {
public void main(String[] args)
{
// SavingAcc saving = new SavingAcc();
}
public class Account
{
int accountNum= 0;
private double balance = 0;//yu e
private double yearInterest = 0;
private String openDate = null ;
Account(int accountNum , double balance , double yearInterest ,String openDate)
{
this.accountNum = accountNum;
this.balance = balance ;
this.yearInterest = yearInterest ;
this.openDate = openDate ;
System.out.print("this is Account class");
}
// Account(){}
public double getBanlance()
{
return balance;
}
public void deposit(double depositMoney)
{
balance += depositMoney ;
}
public void drawMoney(double DMoney)
{
balance -=DMoney;
}
}
}
package pkg;import pkg.test9_3.Account;public class SavingAcc extends Account { SavingAcc(test9_3 test9_3, int accountNum, double balance,double yearInterest, String openDate) {
test9_3.super(accountNum, balance, yearInterest, openDate);
// TODO Auto-generated constructor stub
if(this.getBanlance() < 0)
{
System.out.println("your Account's balance is lower than $0");
}
else
;
}
}
如果是这样,并参考访问控制:
public 可以被所有其他类访问
protect 自身,子类及同一个包中类可以访问
private 只能被自身访问和修改
package 同一个包中的类可以访问public肯定是不行的,private也是不行的,protect对所有子类都一样。
看来只能是package了,通过放在不同的包中加以控制了。
学习下怎么写proxy,对于不被 允许的访问的 类 进行阻止
protect 自身,子类及同一个包中类可以访问
private 只能被自身访问和修改
package 同一个包中的类可以访问lz加油
@Override
public void drawMoney(double DMoney) {
throw new UnsupportedOperationException();
}
这是一种方案,还可以定义接口,save的时候不实现这个接口