我有一些两个子类共有的方法,所以我把它们放在抽象超类中,但是有一种方法使用具有两个不同值的变量,所以我很困惑如何实现该方法,代码如下:
StandardMember 类在开始时得到了这个方法,它有自己不同的值,residualCredit=30
public void borrowHolding(int holdingId)
throws InsufficientCreditException, MultipleBorrowingException {
// TODO Auto-generated method stub
System.out.println("Hello");
Holding tempHolding = Library.libCollection.getHolding(holdingId);
if (Library.libCollection.getHolding(holdingId) != null) {
if (tempHolding.isOnLoan()) {
System.out.println("Can not be issued Currently on Load");
} else {
System.out.println("Can be issued");
remainingCredit-=tempHolding.getDefaultLoanFee();
System.out.println(getRemainingCredit());
tempHolding.setLoanCheck(true);
currentlyBorrowedHolding.put(holdingId, tempHolding);
System.out.println(remainingCredit);
System.out.println(holdingId);
}
}
PremiumMember 类获得了相同的方法,但剩余信用的值是 45,而它们共有的所有方法都在实现Member 接口的 AbstractMember 类中实现。但是当我尝试从其他类调用这些方法时,我必须像这样在库类中初始化 AbstractMember 的对象
Member member = new StandardMember();
这非常糟糕,因为我不能使用 StandardMember 对象来运行 PremiumMember 对象的相同方法版本。所以,要么我应该创建 PremiumMember 类的新对象,要么我不知道该怎么做。但是如果我创建了两个对象,那么这个成员对象将被用在 borrowHolding 方法中,该方法基本上是 Library Class 中的级联方法,它反过来调用 Member Interface 中的 borrowHolding 方法:
public void borrowHolding(int holdingId) throws InsufficientCreditException, MultipleBorrowingException {
if(libCollection.holdingMap==null){
System.out.println("Collection is Empty");
}
if(libCollection.holdingMap.containsKey(holdingId))
member.borrowHolding(holdingId);
}
问题是我不能创建两个对象,因为在运行时我只能调用一个方法。所以帮我弄清楚如何在抽象类中实现这个方法,这样程序就会检测到它应该创建哪个对象的差异。