我认为创建更通用的类会更好(而且很容易),它能够处理你传递给它的任何年数:
public class Period {
int[] years;
Period() {
}
Period(String periode) {
String[] periodeSplit = periode.split("-");
years = new int[periodeSplit.length];
for (int i = 0; i < periodeSplit.length; i++) {
years[i] = Integer.parseInt(periodeSplit[i]);
}
}
public String toString() {
String result = "";
for (int i = 0; i < years.length; i++) {
result += "Year " + i + ":" + years[i] + "\n";
}
return result;
}
}
如果原始类确实需要扩展,则可以这样做:
class ExtendedPeriod extends Period {
int thirdPart;
ExtendedPeriod(String periode) {
String[] periodeSplit = periode.split("-");
this.firstYear = Integer.parseInt(periodeSplit[0]);
this.secondYear = Integer.parseInt(periodeSplit[1]);
this.thirdPart = Integer.parseInt(periodeSplit[1]);
}
public String toString() {
return "Day: " + this.firstYear + "\n" + "Month: " + this.secondYear
+ "\nYear: " + this.thirdPart;
}
}
我建议将变量名称“firstYear”和“secondYear”更改为不同的名称,例如“firstPart”、“secondPart”,因为对于extendedPeriod,它们不再是年份(我将它们留在我的代码中,因此它可以与你的代码一起编译,但称为新的 int 'thirdPart')。我不认为这是继承的最佳用途,但如果这是需要的话。我还想像这样重用 Period 中的 toString :
public String toString2() {
return super.toString() + "\nThird part: " + this.thirdPart;
}
但要让它有意义,您必须在 Period 中更改 toString 方法,而不是调用值“年”。