这是我班的特色:
我必须重写toString方法以使每个类都打印出来:
“[Superclass]: [name-of-superclass] ---[subclass]: [name-of-subclass]”
我有每个类的名称的getter getDescription
我知道对于子类,它们只需要执行super.getDescription和this.getDescription。
但是我不了解超类LivingRoomItem,它怎么能从其子类中调用所有的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() ;
}
}
最佳答案
您的思路是正确的,也许只有您的执行不正确。
考虑以下类别:
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
。希望我能为您服务!