来自父类和子类的继承获取器

时间:2018-11-30 00:25:11

标签: java inheritance arraylist getter

这是我班的特色: enter image description here

我必须重写toString方法以使每个类都打印出来:

“[Superclass]: [name-of-superclass] ---[subclass]: [name-of-subclass]”

每个类的名称都有getter getDescription

我知道对于子类,它们只需要执行super.getDescription和this.getDescription。

  1. 但是我不了解超类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() ;
}

}

1 个答案:

答案 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)));
}

结果: enter image description here


我对您的toString有帮助,出于锻炼目的,您可以在超类toString中使用instanceof运算符:

示例(在您的LivingRoomItem类内部):

return (this instanceof Sofa ? "Superclass... Subclass: Sofa" : "Regular LivingRoomItem toString");

但是就像我说的那样,我相信将Object显示为超类是正确的:)并且仅在子类上显示LivingRoomItem

希望我能帮助您!