应该继承package-private字段,还是在所有子类中创建私有字段?

时间:2018-11-24 13:03:04

标签: java inheritance private

我很难理解某些类字段的继承。 如果所有子类中都有一个字段,但是所有子类中的字段都不相同,那么我应该如何编码呢?​​

我应该这样编码吗:

class Product {
    private String name;
    double tax;

    Product(String name) {
        this.name = name;
    }
}

class CarProduct extends Product {
    CarProduct(String name) {
        super(name);
        this.tax = 0.2;
    }
}

class PharmacyProduct extends Product {
    PharmacyProduct(String name) {
        super(name);
        this.tax = 0.05;
    }
}

还是这样?哪个更正确?

class Product {
    private String name;

    Product(String name) {
        this.name = name;
    }
}

class CarProduct extends Product {
    private double tax;

    CarProduct(String name) {
        super(name);
        this.tax = 0.2;
    }
}

class PharmacyProduct extends Product {
    private double tax;

    PharmacyProduct(String name) {
        super(name);
        this.tax = 0.05;
    }
}

更新 在@JB Nizet评论之后,我更改了为每个子类设置税值的方法:

class Product {
    private String name;
    private double tax;

    Product(String name) {
        this.name = name;
    }

    setTax(double tax) {
        this.tax = tax;
    }
}

class CarProduct extends Product {
    CarProduct(String name) {
        super(name);
        this.setTax(0.5);
    }
}

class PharmacyProduct extends Product {
    PharmacyProduct(String name) {
        super(name);
        this.setTax(0.05);
    }
}

这比前两个更好吗?

1 个答案:

答案 0 :(得分:0)

如果税收是所有产品应具有的共同财产(对我来说很有意义,但要取决于您的确切用例),那么我将const Square = function Square() { this.piece = null; this.is = { king: () => this.piece === "K", queen: () => this.piece === "Q" }; }; const square = new Square(); square.piece = 'K'; console.log(square.is.king()); console.log(square.is.queen());成员保留在基类中,并拥有继承类将其值传递给基本构造函数:

tax