发出重写tostring

时间:2013-02-19 20:31:15

标签: java override tostring

我想在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;
    }
}

CargoShip类:

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]);
        }
    }
}

1 个答案:

答案 0 :(得分:4)

CargoShip中,您有以下内容:

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

通过调用super.toString(),您实际上正在调用父类toString()方法,其中包含年份的打印。您应该删除该方法调用并更改返回的String以仅包含您要显示的信息。

覆盖父方法意味着提供具有相同名称,参数列表,返回类型和可见性的方法,并且可能具有可能不同的实现(方法体)。您无需致电super即可将其视为覆盖。

您可能希望CargoShip中有类似内容:

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