Question

sorry for the question being ambiguous, but I found it hard to word the title right.

I have a super class with a method called calculateTotal() and a method called toString(). I also have a sub class that overrides both method.

The problem I'm having is, when I call toString() from subclass, super.toString() portion returns a string with the value returned from calculateTotal() from subclass. Therefore I'm getting same value for Total: and Grand Total:, both being the value of handlingFee added.

To illustrate the problem, here is an example output.

Expected Output: Total: 20, Plus a handling charge of $4, Grand Total: $24

Current Output: Total: 24, Plus a handling charge of $4, Grand Total: $24

Any help or suggestion would be appreciated! Thank you,

Codes:

Super Class:

public class SuperClass {
    private double unitPrice;
    private int quantityOrdered;

    public double calculateTotal() {

        return unitPrice * quantityOrdered;
    }

    public String toString() {

        return String.format("\nUnit Price: %.2f\nQuantity Ordered: %d\nTotal: %.2f", unitPrice, quantityOrdered, calculateTotal());
    }
}

Sub Class:

public class SubClass extends SuperClass {

    private double handlingFee;
    public double calculateTotal() {

        return unitPrice * quantityOrdered + handlingFee;
    }

    public String toString() {

        return String.format("%s\nPlus a $%.2f handling charge\nGrand Total: $%.2f", super.toString(), handlingFee, calculateTotal());
    }
}
Was it helpful?

Solution

When you have an instance of the subclass, you don't also have a separate instance of the super class. So when the super classes method calls calculateTotal() it calls the lowest (down the subclass chain) method defined for that signature.

Sounds like you might want a calculateSubTotal() method that is not overridden in the subclass because you don't what the calculation of the subtotal in the super class to be changed by subclasses.

OTHER TIPS

This pattern is often seen in the JDK or the Spring Framework, The superclass is an abstract class like so:

public abstract class A {

    public void method1(){
        method2();
    }
    public abstract void method2 (); 
}


public class B extends A {

    @Override
    public void method2(){
        System.out.println("method2 has been called");
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top