0

我想在Ship类的toString方法中覆盖CargoShip类的toString方法,这样控制台就不会打印船的建造年份。我试过这样做,但它仍然打印年份。我不确定我是否对覆盖进行了错误的编码,或者问题是否与在ShipDemo类中调用方法的方式有关。

船级:

public class Ship {
    public String shipName;
    public String yearBuilt;

    public Ship() {
    }

    public Ship(String name, String year) {
        shipName = name;
        yearBuilt = year;
    }

    public void setShipName(String name) {
        shipName = name;
    }

    public void setYearBuilt(String year) {
        yearBuilt = year;
    }

    public String getShipName() {
        return shipName;
    }

    public String getYearBuilt() {
        return yearBuilt;
    }

    public String toString() {
        //return toString() + " Name: " + shipName
        //+ "\n Year Built: " + yearBuilt;
        String str;
        str = " Name: " + shipName + "\n Year Built: " + yearBuilt;

        return str;
    }
}

货船类:

public class CargoShip extends Ship {
    public int capacity;

    public CargoShip() {
    }

    public CargoShip(int maxCap, String name, String year) {
        super(name, year);
        capacity = maxCap;
    }

    public int getCapacity() {
        return capacity;
    }

    public void setCapacity(int cap) {
        cap = capacity;
    }

    public String toString() {
        return super.toString() + " Name: " + getShipName()
                + " Tonnage Capacity: " + getCapacity();
    }
}

ShipDemo类:

public class ShipDemo {
    public static void main(String[] args) {
        // Array Reference
        Ship[] shiptest = new Ship[3];

        // Elements in array set to ship type
        shiptest[0] = new Ship();
        shiptest[1] = new CargoShip();
        shiptest[2] = new CruiseShip();

        // Ship 1
        shiptest[0].setShipName("Manitou ");
        shiptest[0].setYearBuilt("1936 ");

        // Ship 2 ; Cargoship
        shiptest[1] = new CargoShip(13632, "SS Edmund Fitzgerald", "1958");

        // Ship 3 ; Cruiseship
        shiptest[2] = new CruiseShip(2620, "RMS Queen Mary 2", "2004");

        // loop to print out all ship info
        for (int i = 0; i < shiptest.length; i++) {
            // Output
            System.out.println("Ship " + i + " " + shiptest[i]);
        }
    }
}
4

1 回答 1

4

CargoShip您有以下内容:

public String toString()
{       
    return super.toString() + " Name: " + getShipName() + " Tonnage Capacity: "      + 
    getCapacity();    
}

通过调用super.toString(),您实际上是在调用父类toString()方法,其中包括年度打印。您应该删除该方法调用并将返回的字符串更改为仅包含您要显示的信息。

覆盖父方法意味着提供具有相同名称、参数列表、返回类型和可见性的方法,但实现可能不同(方法体)。您无需调用super即可将其视为压倒一切。

您可能希望在CargoShip

public String toString()
{       
    return " Name: " + getShipName() + " Tonnage Capacity: " + getCapacity();    
}
于 2013-02-19T20:33:42.153 回答