Search code examples
javasuperclass

Subclass method doesn't subtract correctly


My task: Create an Account super class and a StudentAccount subclass. The StudentAccount is different in that they get a bonus $1 for a deposit but a $2 fee for withdrawal. I overrided the superclass methods for the methods in the subclass. The only method that doesn't seem to work is my withdrawal one.

public class BankTester
{
    public static void main(String[] args)
    {
        Account deez = new Account("Bob", 10.0);
        Account jeez = new StudentAccount("Bobby", 10.0);

        jeez.withdrawal(2.0);
        System.out.println(jeez);

        deez.withdrawal(2.0);
        System.out.println(deez);

    }
}


public class Account
{
private String name;
private double balance;

// Initialize values in constructor
public Account(String clientName, double openingBal){
   name = clientName;
   balance = openingBal;
}

// Complete the accessor method
public double getBalance(){
    return balance;

}

// Add amount to balance
public void deposit(double amount){
   balance += amount;

}

// Subtract amount from balance
public void withdrawal(double amount){
    balance -= amount;

}

// Should read: Regular account with a balance of $__.__
public String toString(){
   return "Regular account with a balance of $" + balance;

}
}


public class StudentAccount extends Account
{
   // Complete this class with Override methods.   

    public StudentAccount(String studentName, double 
openingBal){
        super(studentName, openingBal);
    }

    // Students get a $1 bonus on depositing
    @Override
    public void deposit(double amount){
       super.deposit(amount + 1);

    }


    // Students pay a $2 fee for withdrawing
    @Override
    public void withdrawal(double amount){
        super.withdrawal(amount - 2);   
    }

    // toString() Should read: Student account with a 
balance of $__.__
    @Override
    public String toString(){
       return "Student account with a balance of $" + 
super.getBalance();

    }
}

Solution

  • You're withdrawing 2 less than the amount - let's say the student wants to withdraw 10, they get 10 but their balance goes down by 8. You're giving the student a credit of 2 for every withdrawal.

    You probably mean

    public void withdrawal(double amount){
        super.withdrawal(amount + 2);   
    }