![](/img/trans.png)
[英]Java runtime method selection using “super” in the subclass and “this” in the super class
[英]Super class method using subclass method
抱歉,這個問題模棱兩可,但我發現很難用正確的標題來表達。
我有一個超類,其中有一個稱為calculateTotal()的方法和一個名為toString()的方法。 我還有一個重寫這兩個方法的子類。
我遇到的問題是,當我從子類調用toString()時,super.toString()部分返回一個字符串,該字符串的值是從子類的calculateTotal()返回的。 因此,我得到的Total:和Grand Total:的值相同,這兩個值都是所增加的handlingFee的值。
為了說明問題,這是示例輸出。
預期產量:總計:20,另加手續費4美元,總計:24美元
當前產出:總計:24,另加手續費$ 4,總計:$ 24
任何幫助或建議,將不勝感激! 謝謝,
代碼:
超級班級:
public class SuperClass {
private double unitPrice;
private int quantityOrdered;
public double calculateTotal() {
return unitPrice * quantityOrdered;
}
public String toString() {
return String.format("\nUnit Price: %.2f\nQuantity Ordered: %d\nTotal: %.2f", unitPrice, quantityOrdered, calculateTotal());
}
}
子類:
public class SubClass extends SuperClass {
private double handlingFee;
public double calculateTotal() {
return unitPrice * quantityOrdered + handlingFee;
}
public String toString() {
return String.format("%s\nPlus a $%.2f handling charge\nGrand Total: $%.2f", super.toString(), handlingFee, calculateTotal());
}
}
當您擁有子類的實例時,您也沒有超類的單獨實例。 因此,當超類方法調用calculateTotal()
它將調用為該簽名定義的最低方法(在子類鏈的下游)。
聽起來您可能想要在子類中不重寫的computeSubTotal()方法,因為您不希望子類更改超類中小計的計算。
這種模式經常在JDK或Spring Framework中出現 ,超類是一個抽象類,如下所示:
public abstract class A {
public void method1(){
method2();
}
public abstract void method2 ();
}
public class B extends A {
@Override
public void method2(){
System.out.println("method2 has been called");
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.