方法1:
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方法,必须进行复制并最终维护,这将是一个问题。
方法2:
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方法。我可能不希望其他类能够更改字段,即使在同一个包中也是如此。
方法3:
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);
}
}
使用这种方法并涉及到很多字段时,构造函数的参数数量将会变得非常庞大,这种情况让人感觉不对劲。
看起来这应该是一个常见的问题,因此应该存在某种“最佳实践”。有没有最好的方法处理这个问题?
Vehicle
中声明了私有字段,那么Car
中的私有字段就是多余的。您还可以调查“protected”访问修饰符。 - Fildor