【问题标题】:Should Inherit package-private field or create private one in all subclasses?应该继承包私有字段还是在所有子类中创建私有字段?
【发布时间】:2019-04-26 18:11:59
【问题描述】:

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

我应该这样编码吗:

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

这比前两个好吗?

【问题讨论】:

  • 您可以将Products 抽象化。有了这个,第一种方法似乎没问题,因为tax 是所有is-a Products 的共同点
  • 但是类的字段不应该尽可能的封装吗?即使我们必须在每个子类中复制诸如纳税申报之类的代码?
  • 您根本不应该有税字段。只是一个方法 getTax() 总是返回相同的值。此外,Java 是否有名为 Strings、Integers、Doubles 的类?不,因为 String 类的一个实例是 one String。从你的类名中删除s:这会使代码变得笨拙且难以阅读。
  • 你没有关注我的评论。你仍然有一个无用的税收领域。相反,您应该在基类中有一个抽象的 getTax() 方法,并在每个子类中返回一个常量的实现。不需要任何字段。
  • 对不起,JB Nizet,我是 OOP 的菜鸟。必须学习抽象...

标签: java inheritance private


【解决方案1】:

如果税收是所有产品都应具有的共同属性(这对我来说很有意义,但取决于您的确切用例),我会将 tax 成员保留在基类中,并让继承类通过它基础构造函数的值:

class Product {
    private String name;
    double tax;

    Product(String name, double tax) {
        this.name = name;
        this.tax = tax;
    }
}

class CarProduct extends Product {
    CarProduct(String name) {
        super(name, 0.2);
    }
}

class PharmacyProduct extends Product {
    PharmacyProduct(String name) {
        super(name, 0.05);
    }
}

【讨论】:

  • 在我的用户案例中,我希望为每个子类固定税款,而不是由用户设置。所以它只能在实例化时由子类设置。我更新了我的问题以显示另一种可能的解决方案。
  • @LuísAlves "仅在实例化时由子类设置" 这正是上面代码所做的。
  • 但这不是和我的第一个选项一样吗?
  • @LuísAlves 它很相似,但并不完全相同。在您的第一个选项中,您让继承类直接操作tax。通过这种方式,他们无法直接访问它,并且可以使用 getter 和 setter(诚然,此处未显示)进行更好的封装。
猜你喜欢
  • 1970-01-01
  • 2022-01-04
  • 2020-10-25
  • 1970-01-01
  • 1970-01-01
  • 2013-01-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多