user8705857
user8705857

Reputation: 1

How to Override a method based on a condition

In my BOOKING class I have this method to calculate the total amount

public void calcTotal(){
    total = amount*priceperbooking;

}

I created a subclass called BOOKING_APPLICATION and I want to override the calcTotal() method if amount > 5 then it must subtract 15% of the total

Here is what I tried but it does not work:

public void calcTotal(){
 if (super.amount>5) {
     super.total = super.total-(15/100.0*super.total);
 }

}

When I run it its giving me the original total, not taking out 15% What am I doing wrong

Edit: Here is the code of my main class

public class Diving_Adventures{
static BOOKING obj1 = new BOOKING();
static BOOKING_APPLICATION obj2 = new BOOKING_APPLICATION();


public static void main(String[] args) {

    obj1.setName();
    obj1.setNumber();
    obj1.setAmount();
    obj1.setPriceperbooking();
    obj1.calcTotal();
    obj2.calcTotal();



    JOptionPane.showMessageDialog(null, obj1.toString());
}


}

I'm assuming by obj1.calcTotal() it will calculate the total and by obj2.calcTotal it will take out the 15% but it does not work

Here is the full code of my BOOKING class:

private String name;
private int number;
public int amount;
public double priceperbooking;
public double total;





public String getName() {
    return name;
}

public int getNumber() {
    return number;
}

public int getAmount() {
    return amount;
}

public double getPriceperbooking() {
    return priceperbooking;
}

public void setName() {

    this.name =  JOptionPane.showInputDialog("Enter the name");;
}

public void setNumber() {

    this.number = Integer.parseInt(JOptionPane.showInputDialog("Enter the number"));
}

public void setAmount() {

    this.amount =  Integer.parseInt(JOptionPane.showInputDialog("Enter the amount"));
}

public void setPriceperbooking() {

    this.priceperbooking = Double.parseDouble(JOptionPane.showInputDialog("Enter the price per bookin"));;
}


public void calcTotal(){
    total = amount*priceperbooking;

}





@Override
public String toString() {
    return "Customer name: "+name+"\n"+"number"+ number + "\namount=" + amount + 
            "\n priceperbooking=" + priceperbooking + "\n total=" + total ;
}

Upvotes: 0

Views: 637

Answers (1)

In your derived class:

public void calcTotal() {
    total = super.calcTotal();
    if (amount > 5) {
       total = total - (15/100.0 * total); 
    }
}

You are mising on calculating the total first, as mentioned.

Upvotes: 2

Related Questions