I’m trying to change the VAT rate of an item depending if it’s a luxury item or not.
I’ve tried using an if inside of my set method but it only uses the pre-set value that I gave it.
private double vat = 0.08;
is my preset value. My get and set methods are:
public double getVat() {
return this.vat;
}
public void setVat(double vat) {
if(lux=true) {
this.vat = 0.10;
}
else if(lux=false) {
this.vat = vat;
}
}
and the variable lux
is
private boolean lux;
Also, this is what my constructor looks like:
public ProductTest(String pname, double price, boolean lux) {
this.pname = pname;
if(price>0) {
this.price = price;
}
else {
this.price = 0;
}
this.lux = lux; //If product type is luxury , =true ----- if product type is not luxury, =false
}
When I create and object and mark the lux
variable as true or false, VAT takes the value of 0.08.
ProductTest p = new ProductTest("apple", 10, true);
System.out.println(p.getVat());
Output: 0.08
ProductTest p = new ProductTest("apple", 10, false);
System.out.println(p.getVat());
Output: 0.08
What can I do to overcome this? Thanks.
>Solution :
You nede to call setVat
in the constructor to apply the logic
public ProductTest(String pname, double price, boolean lux) {
this.pname = pname;
this.price = Math.max(0, price);
this.lux = lux;
setVat(vat);
}
public void setVat(double vat) {
if (lux) {
this.vat = 0.10;
} else {
this.vat = vat;
}
}
Could even be shorter with ternary operator
public void setVat(double vat) {
this.vat = lux ? 0.10 : vat;
}
Or do it differently by putting the logic in the getVat
public ProductTest(String pname, double price, boolean lux) {
this.pname = pname;
this.price = Math.max(0, price);
this.lux = lux;
}
public double getVat() {
return lux ? 0.10 : vat;
}
public void setVat(double vat) {
this.vat = vat;
}