我必须重写toString方法以使每个类都打印出来:
“[Superclass]: [name-of-superclass] ---[subclass]: [name-of-subclass]”
每个类的名称都有getter getDescription
我知道对于子类,它们只需要执行super.getDescription和this.getDescription。
编辑:
class livingRoomItem{
int id;
double price;
String color;
String description = "livingRoomItem";
livingRoomItem(int id, double price, String color, String description){
this.id = id;
this.price = price;
this.color = color;
this.description = description;
}
@Override
public String toString(){
return "[Superclass] :" + this.description + "----" + "[subclass]: ";
}
public String getDescription() {
return "livingRoomItem";
}
public void setDescription(String description) {
this.description = description;
}
class Sofa extends livingRoomItem{
private int seater;
Sofa(int id, double price, String color, String description, int seater){
super(id, price, color, description);
this.seater = seater;
}
@Override
public String getDescription(){
return "Sofa";
}
public int getSeater() {
return seater;
}
public void setSeater(int seater) {
this.seater = seater;
}
@Override
public String toString(){
return "[Superclass] :" + super.getDescription() + "----" + "[subclass]: "+ this.getDescription() ;
}
}
答案 0 :(得分:1)
您的思路是正确的,也许只有您的执行不正确。
考虑以下类别:
public class LivingRoomItem
public class Sofa extends LivingRoomItem
public class Table extends LivingRoomItem
public class Lighting extends LivingRoomItem
您可以按LivingRoomItem
的身份处理所有这些
在您的calculatePrice方法中,将按预期使用LivingRoomItem
处理所有对象:
public static BigDecimal calculateTotalPrice(List<LivingRoomItem> items) {
return items.stream().map(item -> item.getPrice()).reduce(BigDecimal.ZERO, BigDecimal::add);
}
由于您要实例化所有对象本身(而不是LivingRoomItem
)并设置价格,因此它应该可以正常工作:
public static void main(String[] args) {
Sofa sofa = new Sofa();
sofa.setPrice(BigDecimal.valueOf(200L));
Lighting lighting = new Lighting();
lighting.setPrice(BigDecimal.valueOf(652L));
Table table = new Table();
table.setPrice(BigDecimal.valueOf(598L));
System.out.println(PriceUtil.calculateTotalPrice(Arrays.asList(sofa, lighting, table)));
}
我对您的toString
有帮助,出于锻炼目的,您可以在超类toString
中使用instanceof运算符:
示例(在您的LivingRoomItem
类内部):
return (this instanceof Sofa ? "Superclass... Subclass: Sofa" : "Regular LivingRoomItem toString");
但是就像我说的那样,我相信将Object
显示为超类是正确的:)并且仅在子类上显示LivingRoomItem
。
希望我能帮助您!