【发布时间】:2017-04-19 19:47:17
【问题描述】:
我无法在这三种处理子类和超类的字段变量的方法之间做出选择。
方法一:
public abstract class Vehicle {
public abstract int getNumberOfWheels();
public abstract int getCost();
}
public class Car extends Vehicle {
private int numberOfWheels;
private int cost;
public Car() {
this.numberOfWheels = 4;
this.cost = 10000;
}
public int getNumberOfWheels() {
return numberOfWheels;
}
public int getCost() {
return cost;
}
}
使用这种方法,我必须在 Vehicle 的每个子类中实现相同的重复 getter 方法。我想这将是更复杂的 getter 方法的问题,必须复制并最终维护。
方法二:
public abstract class Vehicle {
private int numberOfWheels;
private int cost;
public int getNumberOfWheels() {
return numberOfWheels;
}
public int getCost() {
return cost;
}
public void setNumberOfWheels(int numberOfWheels) {
this.numberOfWheels = numberOfWheels;
}
public void setCost(int cost) {
this.cost = cost;
}
}
public class Car extends Vehicle {
private int numberOfWheels;
private int cost;
public Car() {
super.setNumberOfWheels(4);
super.setCost(10000);
}
}
使用这种方法,我必须实现我可能不想拥有的 setter 方法。我可能不希望其他类能够更改字段,即使在同一个包中也是如此。
方法三:
public abstract class Vehicle {
private int numberOfWheels;
private int cost;
public class Vehicle(int numberOfWheels, int cost) {
this.numberOfWheels = numberOfWheels;
this.cost = cost;
}
public int getNumberOfWheels() {
return numberOfWheels;
}
public int getCost() {
return cost;
}
}
public class Car extends Vehicle {
private int numberOfWheels;
private int cost;
public Car() {
super(4, 10000);
}
}
用这种方法,加上很多字段,构造函数的参数量会变大,感觉不对。
这似乎是一个足够普遍的问题,以至于存在某种“最佳实践”。有没有最好的方法来做到这一点?
【问题讨论】:
-
Car中的私有字段如果在Vehicle中声明,则它们是多余的。您可能还想调查“protected”访问修饰符。
标签: java inheritance field subclass superclass