javahierarchy

Unexpected output while dealing with hierarchies in Java


i was working on a school worksheet when i stumbled on this problem. I have the vehicle class as such:

public class Vehicle {
private static int idcouter = 0;

private int id;
private Condition condition;
private int price;

public Vehicle() {
    this.id = idcouter++;
    this.condition = condition;
    this.price = price;
}

public Condition getCondition() {
    return condition;
}

public void setCondition(Condition condition) {
    this.condition = condition;
}

public int getPrice() {
    return price;
}

public void setPrice(int price) {
    this.price = price;
}}

And Truck as such:

public class Truck extends Vehicle {
private boolean trailer;

public Truck() {
    super();
    this.trailer = trailer;
}

@Override
public void setPrice(int price) {
    if (this.getCondition() == enums.Enums.Condition.NEW) {
        if (this.trailer) {
            int tempPrice = (int) (price * 0.95f);
            super.setPrice(tempPrice);
        } else {
            super.setPrice(price);
        }
    } else {
        int tempPrice = (int) (price * 0.85f);
        super.setPrice(tempPrice);
    }
}}

Given my main:

    Truck t1 = new Truck();
    Truck t2 = new Truck();
    Truck t3 = new Truck();
    t1.setPrice(200);
    t2.setPrice(200);
    t3.setPrice(200);
    
    t1.setCondition(enums.Enums.Condition.NEW);
    t1.setTrailer(true);
    
    t2.setCondition(enums.Enums.Condition.NEW);
    t2.setTrailer(false);
    
    t3.setCondition(enums.Enums.Condition.USED);
    t3.setTrailer(true);
    
    System.out.println("Price: " + t1.getPrice());
    System.out.println("Price: " + t2.getPrice());
    System.out.println("Price: " + t3.getPrice());

Why is my output:

Price: 170

For all the trucks 1,2 and 3.

It makes no sense, it should be overriding it. I did something similar with Car, a sub class of vehicle and it worked perfectly. I´ve tried different things but i can't understand what's happening. If anyone could share some information or point me in the right direction I would appreciate it. Thanks in advance.


Solution

  • It's because the value of the member variable trailer is false for all instance of Truck (t1,t2, t3). The method setPrice is called before the setTrailer is called.

    The logic of setPrice will always see trailer as false which is the default value for a native boolean. If trailer would be of type Boolean the setPrice method would throw a NullPointerExcpetion for all calls of setPrice(200).

    The assignments in the constructors of Truck and Vehicle are useless because the constructors have no arguments which could be assigned to this.xxxxx variables.