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