我真的被 Goodrich 和 Tamassia 的“数据结构和算法”中的这个问题难住了。本书介绍了以下两个类:
public class CreditCard {
private String customer;
private String bank;
private String account;
private int limit;
protected double balance;
public CreditCard(String customer, String bank, String account, int limit, double balance) {
this.customer = customer;
this.bank = bank;
this.account = account;
this.limit = limit;
this.balance = balance;
}
public CreditCard(String customer, String bank, String account, int limit) {
this(customer, bank, account, limit, 0.0);
}
public String getCustomer() { return this.customer; }
public String getBank() { return this.bank; }
public String getAccount() { return this.account; }
public int getLimit() { return this.limit; }
public double getBalance() { return this.balance; }
public boolean charge(double price) {
if(price + this.balance > this.limit)
return false;
this.balance += price;
return true;
}
public void makePayment(double amount) {
if( amount < 0)
System.out.println("Cannot process negative payment");
else
this.balance -= amount;
}
public void updateCreditLimit() {
this.limit -= balance;
}
public static void printSummary(CreditCard card) {
System.out.println("Customer = " + card.customer);
System.out.println("Bank = " + card.bank);
System.out.println("Account = " + card.account);
System.out.println("Balance = " + card.balance);
System.out.println("Limit = " + card.limit);
}
}
子类
public class PredatoryCreditCard extends CreditCard {
private double apr;
public PredatoryCreditCard(String customer, String bank, String account,
int limit, double balance, double apr) {
super(customer, bank, account, limit, balance);
this.apr = apr;
}
public void processMonth() {
if(this.balance > 0) {
double monthlyFactor = Math.pow(1 + apr, 1F/12);
this.balance *= monthlyFactor;
}
}
public boolean charge(double price) {
boolean isSuccess = super.charge(price);
if(!isSuccess)
this.balance += 5;
return isSuccess;
}
}
问题:
假设我们更改 CreditCard 类,以便实例变量 balance
具有私有(private)可见性。为什么 PredatoryCreditCard.charge 方法的以下两个实现存在缺陷?
public boolean charge(double price) {
boolean isSuccess = super.charge(price);
if(!isSuccess)
charge(5); //penalty for late fee
return isSuccess;
}
第二个:
public boolean charge(double price) {
boolean isSuccess = super.charge(price);
if(!isSuccess)
super.charge(5); //penalty for late fee
return isSuccess;
}
据我所知,子类不能直接操作其父类(super class)的私有(private)字段。该字段必须是 protected 或公共(public)的。这允许我们在子类中说 this.balance += 5
。我对原则的理解不是问题,我的问题是我被要求回答的问题。从实现的角度来看,我可以在 PredatoryCreditCard.charge 方法中清楚地看到任何缺陷,因为在问题提供的新实现的两种情况下,我们都会更改类的余额字段,因为调用极好的。我找不到新实现中的缺陷,除非我认为我的继承知识存在一些漏洞。
提前谢谢您。
最佳答案
无论哪种情况,如果您的余额足够接近费用(值(value) 5)将超出您的限额,则不会向您收取费用。在第一种情况下:
public boolean charge(double price) {
boolean isSuccess = super.charge(price);
if(!isSuccess)
charge(5); //penalty for late fee
return isSuccess;
}
当 isSuccess
失败时会发生什么?我们陷入无限递归调用 this.charge(...)
关于java - java中私有(private)成员变量的子类访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32727194/