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 に答える