gpt4 book ai didi

java - 子类/父类(super class)字段的最佳实践

转载 作者:行者123 更新时间:2023-11-30 07:57:42 28 4
gpt4 key购买 nike

<分区>

我在决定这三种处理子类和父类(super class)字段变量的方法时遇到了困难。

方法一:

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

用这种方法,加上很多字段,构造函数的参数量会越来越大,感觉不对。

这似乎是一个足够普遍的问题,以至于存在某种“最佳实践”。有没有最好的方法来做到这一点?

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com