我正在学习 Java 类(class),可能的考试问题的解决方案如下(在名为 Parcel 的类中):
private boolean international;
private double weight;
public Parcel(boolean international, double weight){
// It is important to also use encapsulation in the constructor. Here we force all
// variable access through the setter methods. In our example this makes sure that
// all parcels have a negative weight. If later modifications are made to what values
// are acceptable, we only need to change the accessor methods, instead of all pieces of code
// that modify the variable.
this.setInternational(international);
this.setWeight(weight);
}
public double getShippingPrice(){
// Also in this case it is recommended to use the accessor method instead of directly accessing the variable
if(this.isInternational()){
return (15 + 7*this.getWeight());
} else {
return (5 + 4*this.getWeight());
}
}
public boolean isInternational(){
return this.international;
}
public void setInternational(boolean international){
this.international = international;
}
public double getWeight(){
return this.weight;
}
public void setWeight(double weight){
if(weight >= 0){
this.weight = weight;
}
else{
throw new IllegalArgumentException("A package cannot have a negative weight");
}
}
我理解为什么封装对于国际化很有用:通过这样做,我们可以确保给定的值是我们想要的值,并在需要时抛出异常。但是,我不明白为什么您需要在 get getShippingPrice()
方法中使用这种工作方式。为什么需要 getter isInternational
,为什么不使用 international
?在编写它们的同一个类中使用 getter 和 setter 有什么好处?我已经回答了后者,至少部分回答了:它使您可以更好地控制输入。但为什么要使用 setter/getter 呢?
最佳答案
我认为有两种情况。
第一个是您可以在未来的类后继者中重写这些 getter,因此这些 getter 可以有另一个实现。
另一种情况,getter 内部的一些特殊逻辑,例如 null
字段可以获取初始值。此方法通常用于自动生成的带有 JAXB
注释的 bean 中的集合字段的 getter:
public List<String> getList() {
if (this.list == null) {
this.list = new ArrayList<>();
}
return this.list;
}
关于java - 在同一个类的方法中使用封装getter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34708070/