我有一個抽象類,割草機,覆蓋toString()方法。草坪拖拉機類擴展割草機。它覆蓋了toString()方法並將super.toString()作爲方法的第一行。然後我有一個商業類擴展LawnTractor並覆蓋toString(),並在其第一行中調用super.toString()。 實例化一個Commercial對象(聲明爲Mower對象)並調用它的toString()我希望它打印來自割草機和草坪拖拉機的兩個屬性,然後它是自己的屬性。相反,它只打印來自割草機的屬性,然後它自己的屬性。我如何調用或重寫商業中的toString()方法,以便它調用其父(LawnTractor)toString()而不僅僅是超級類(割草機)。如何從父類調用重寫的方法而不是超類?
public abstract class Mower {
private String manufacturer;
private int year;
private String serialNumber;
public String tostring(){
String temp = "Manufacturer: " + getManufacturer() + "\nYear: " + getYear() + "\nSerial Number:" + getSerialNumber() + "\n";
return temp;
}
}
public class LawnTractor extends Mower{
private Engine engine = new Engine();
private String model;
private double deckWidth;
public LawnTractor(){
super();
}
public String toString(){
String temp = super.tostring() + "Engine:\n" + getEngine().toString() + "\nModel: " + getModel() + "\nDeck Width: " + getDeckWidth() + "\n";
return temp;
}
public class CommercialMower extends LawnTractor {
private double operatingHours;
private boolean zeroTurnRadius;
public CommercialMower(){
super();
}
public String toString(){
String temp = super.toString() + "Operating Hours: " + getOperatingHours() + "\nZero Turn Radius: " + isZeroTurnRadius() + "\n";
return temp;
}
請在您的描述之外添加代碼片段 – Hristo
所以我發現在NetBeans中,我需要通過在方法菜單打開時查看它的javaDoc來指定要調用哪個super.toString()。但是當我將我的代碼交給我的教授時,這種選擇是否會轉移?有沒有辦法保證我的決定? – Jordyn
請告訴我們您的代碼。 –