Vector won't display all inforamtion about an object in command line
The output I though would come up:
Length: XX Width: XX Title: XX Price: XX
The output I actually got:
Title: XX Price: XX
Why the program omitted ClassA's toString?
Main:
case 'c':
if(!theList.isEmpty()){
for (int i = 0; i < theList.size(); i++)
System.out.println(theList.elementAt(i).toString());
} else {
System.out.println("The list is empty!");
}
break;
ClassA's toString():
@Override
public String toString(){
StringBuilder result = new StringBuilder();
result.append("Length: ").append(this.getLength()).append('\n');
result.append("Width: ").append(this.getWidth()).append('\n');
return result.toString();
}
ClassB's, that extends ClassA, toString():
@Overri开发者_高级运维de
public String toString(){
super.toString();
StringBuilder result = new StringBuilder();
result.append("Title: ").append(this.getTitle()).append('\n');
result.append("Price: ").append(this.getPrice()).append('\n');
return result.toString();
}
It's very simple. You only called A's toString
method, but didn't use the return value at all.
Apart from that, I would write the toString
method as follows:
@Override
public String toString() {
return //
"Length: " + getLength() + '\n' + //
"Width: " + getWidth() + '\n';
}
The code is shorter, easier to read and compiles to equivalent bytecode as your current code. Same for B's toString
:
@Override
public String toString() {
return super.toString() + //
"Title: " + getTitle() + '\n' + //
"Price: " + getPrice() + '\n';
}
精彩评论