我想在 CargoShip
类的 toString
方法中重写 Ship
类的 toString
方法,以便控制台不会打印船舶的 build 年份。我尝试过这样做,但它仍然打印年份。我不确定我是否错误地编写了覆盖代码,或者问题是否与在 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]);
}
}
}
最佳答案
在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();
}
关于java - 问题覆盖 tostring,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14966808/