【发布时间】: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