Search code examples
javaencapsulationsettergetter

Using encapsulation getter in methods of the same class


I am following a course on Java and a solution to a possible exam question states the following (in a class called 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");
    }
}

I understand why encapsulation is useful for international: by doing so, we make sure that the given values are the ones we want and throw exceptions where needed. However, I do not understand why you would need such a way of working in get getShippingPrice() method. Why do you need the getter isInternational, and why not use international? What is the advantage of using getters and setters in the same class they are written in? The latter I have already answered, at least partially: it gives you more control over the input. But why use getters?


Solution

  • I think there are two cases.

    First one is that you can override these getters in future class successors, so these getters could have another implementation.

    Another case, some special logic inside getters, for example null fields can obtain initial values. This method is often used for getters of collection fields in auto-generated JAXB-annotated beans:

    public List<String> getList() {
        if (this.list == null) {
            this.list = new ArrayList<>();
        }
        return this.list;
    }