Overriding Methods

  • (2 Pages)
  • +
  • 1
  • 2

28 Replies - 6653 Views - Last Post: 09 July 2011 - 09:59 PM Rate Topic: -----

#16 shango11  Icon User is offline

  • D.I.C Head

Reputation: 3
  • View blog
  • Posts: 78
  • Joined: 06-July 11

Re: Overriding Methods

Posted 07 July 2011 - 09:23 PM

If the method is already overriden how come that when I try to withdraw past zero it gives me the error insufficient funds when it should display the negative amount left on the account?
For example if I try to withdraw 101 the code should display -1 account balance but instead it displays insufficient funds.
Was This Post Helpful? 0
  • +
  • -

#17 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8343
  • View blog
  • Posts: 31,890
  • Joined: 06-March 08

Re: Overriding Methods

Posted 07 July 2011 - 09:30 PM

The witgdraw() method in the Account class shouldn't make any validation
It is there to subtract from the balance the amount of the withdraw that's all
The Account class has no idea of what is a CheckingAccount and what is a SavingAccount and what type of negative balance they authorize or not.

The SavingAccount class and the CheckingAccount class are there to filter if a transaction is permitted or not. They are the one who should display "Yes permitted", "No refuse".
After that they delegate the actual calculations, and maintenance of the balance to their father the Account class.

Hope it is clearer
Was This Post Helpful? 0
  • +
  • -

#18 kiwi_steve  Icon User is offline

  • D.I.C Head

Reputation: 31
  • View blog
  • Posts: 109
  • Joined: 26-September 09

Re: Overriding Methods

Posted 07 July 2011 - 09:55 PM

View Postpbl, on 08 July 2011 - 05:30 PM, said:

The witgdraw() method in the Account class shouldn't make any validation
It is there to subtract from the balance the amount of the withdraw that's all
The Account class has no idea of what is a CheckingAccount and what is a SavingAccount and what type of negative balance they authorize or not.

The SavingAccount class and the CheckingAccount class are there to filter if a transaction is permitted or not. They are the one who should display "Yes permitted", "No refuse".
After that they delegate the actual calculations, and maintenance of the balance to their father the Account class.

Hope it is clearer


Is that the right way to do it? Personally I would have decided that the Account class has no place dealing with a withdrawl since it has no idea how to do it - and just given it a no-op method that had to be overridden and dealt with in the correct manner by each individual account type. If you were going to make a superclass version of withdrawl that actually did the withdrawl, then shouldn't there just be a getAvailableBalance() method in each subclass to determine if it can, then use that method to decide if its a legal amount to deduct?

Then again... if there was only one way to skin a cat, then cat skinners would get very bored B)

This post has been edited by kiwi_steve: 07 July 2011 - 09:56 PM

Was This Post Helpful? 0
  • +
  • -

#19 shango11  Icon User is offline

  • D.I.C Head

Reputation: 3
  • View blog
  • Posts: 78
  • Joined: 06-July 11

Re: Overriding Methods

Posted 07 July 2011 - 10:44 PM

I must not be getting something, now i can withdraw into the negatives but I cant make it stop at -500, it just keeps going. Do I put the balance validation into the Account class but not the withdraw method?

checkingsAccount
import javax.swing.JOptionPane;

public class checkingAccounts extends Account {
	
	public void withdraw(double wd){
		if(wd > balance + 500){
			JOptionPane.showMessageDialog(null, "Insufficient funds");
			return;
		}

		else if(wd < balance + 500){
			super.withdraw(wd);
		}
		
	}
	
	public String toString(){
		return "Checkings Account";
	}
	
}


This post has been edited by shango11: 07 July 2011 - 10:47 PM

Was This Post Helpful? 0
  • +
  • -

#20 kiwi_steve  Icon User is offline

  • D.I.C Head

Reputation: 31
  • View blog
  • Posts: 109
  • Joined: 26-September 09

Re: Overriding Methods

Posted 07 July 2011 - 10:59 PM

In this method, try the following:
	public void withdraw(double wd){
		if(balance + 500 - wd > 0) {
			JOptionPane.showMessageDialog(null, "Insufficient funds");
			return;
		}

		else {
			super.withdraw(wd);
		}
		
	}


This (balance + 500 - wd > 0) Checks if you have enough including the OD...

...and you don't need else if (...) {, just else { since there is only a do it, or don't case

I suspect the OD calculation logic was my fault from earlier in the thread :)

This post has been edited by kiwi_steve: 07 July 2011 - 11:07 PM

Was This Post Helpful? 0
  • +
  • -

#21 shango11  Icon User is offline

  • D.I.C Head

Reputation: 3
  • View blog
  • Posts: 78
  • Joined: 06-July 11

Re: Overriding Methods

Posted 07 July 2011 - 11:41 PM

View Postkiwi_steve, on 07 July 2011 - 10:59 PM, said:

In this method, try the following:
	public void withdraw(double wd){
		if(balance + 500 - wd > 0) {
			JOptionPane.showMessageDialog(null, "Insufficient funds");
			return;
		}

		else {
			super.withdraw(wd);
		}
		
	}


This (balance + 500 - wd > 0) Checks if you have enough including the OD...

...and you don't need else if (...) {, just else { since there is only a do it, or don't case

I suspect the OD calculation logic was my fault from earlier in the thread :)


That doesnt work either, im starting to think that there is something wront with the test program.
Was This Post Helpful? 0
  • +
  • -

#22 kiwi_steve  Icon User is offline

  • D.I.C Head

Reputation: 31
  • View blog
  • Posts: 109
  • Joined: 26-September 09

Re: Overriding Methods

Posted 08 July 2011 - 04:04 AM

Make sure you're creating the correct account:

if(accountType == 1){
    account = new Account(1, 100, .045);
}


You shouldn't be making a new Account - you should be making a new SavingsAccount. Generally making a new object is

SuperClass variableName = new SubClass(params);
or in your case
Account account1 = new SavingsAccount(1, 100, .045);

This post has been edited by kiwi_steve: 08 July 2011 - 04:05 AM

Was This Post Helpful? 0
  • +
  • -

#23 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8343
  • View blog
  • Posts: 31,890
  • Joined: 06-March 08

Re: Overriding Methods

Posted 08 July 2011 - 11:05 AM

View Postkiwi_steve, on 08 July 2011 - 12:55 AM, said:

Is that the right way to do it? Personally I would have decided that the Account class has no place dealing with a withdrawl since it has no idea how to do it - and just given it a no-op method that had to be overridden and dealt with in the correct manner by each individual account type. If you were going to make a superclass version of withdrawl that actually did the withdrawl, then shouldn't there just be a getAvailableBalance() method in each subclass to determine if it can, then use that method to decide if its a legal amount to deduct?

Yes and no. Here we have a simple operation which is

balance -= withdraw;

so you can put it in the CheckingAccount and SavingAccount class.
But imageine that later on, after you have execute: balance -= withdraw; you'll have to:
- register the transaction in a log file
- produce a report for IRS if the withdraw is > 10,000
- update number of withdraw performed during that month
- produce stats for the bank officials on what is the average withdraw to see if larger bills should be put in atm
- send a status to police force because this account is monitored
- ...

you will reproduce the code for that in both subclasses ?

No better to centralized at a single place: balance -= withdraw;
if you add to add later on, you'll be
In the other hand, if charges have to be collected for the withdraw, that should be done in Checking and Saving because they might be different
Was This Post Helpful? 0
  • +
  • -

#24 shango11  Icon User is offline

  • D.I.C Head

Reputation: 3
  • View blog
  • Posts: 78
  • Joined: 06-July 11

Re: Overriding Methods

Posted 08 July 2011 - 12:48 PM

View Postkiwi_steve, on 08 July 2011 - 04:04 AM, said:

Make sure you're creating the correct account:

if(accountType == 1){
    account = new Account(1, 100, .045);
}


You shouldn't be making a new Account - you should be making a new SavingsAccount. Generally making a new object is

SuperClass variableName = new SubClass(params);
or in your case
Account account1 = new SavingsAccount(1, 100, .045);


I tried that but it gives me this error "The constructor savingsAccount(int, int, double) is undefined". Should I make a constructor in the savingsAccount? Isnt the savingsAccount class supposed to inherit all of that from the Account class?
Was This Post Helpful? 0
  • +
  • -

#25 shango11  Icon User is offline

  • D.I.C Head

Reputation: 3
  • View blog
  • Posts: 78
  • Joined: 06-July 11

Re: Overriding Methods

Posted 08 July 2011 - 05:08 PM

I got everything working, but now the logic for calculating the overdraft amount is a bit flawed. I cant seem to be able to find one that works.

Edit: everything is working now. I'll post the final code in a few

This post has been edited by shango11: 08 July 2011 - 05:15 PM

Was This Post Helpful? 0
  • +
  • -

#26 kiwi_steve  Icon User is offline

  • D.I.C Head

Reputation: 31
  • View blog
  • Posts: 109
  • Joined: 26-September 09

Re: Overriding Methods

Posted 08 July 2011 - 09:56 PM

View Postshango11, on 09 July 2011 - 08:48 AM, said:

I tried that but it gives me this error "The constructor savingsAccount(int, int, double) is undefined". Should I make a constructor in the savingsAccount? Isnt the savingsAccount class supposed to inherit all of that from the Account class?


Sounds like you figured it out already, but constructors are not 'methods' as such, and so don't get inherited.

Glad you got it all working :)
Was This Post Helpful? 0
  • +
  • -

#27 kiwi_steve  Icon User is offline

  • D.I.C Head

Reputation: 31
  • View blog
  • Posts: 109
  • Joined: 26-September 09

Re: Overriding Methods

Posted 08 July 2011 - 10:01 PM

View Postpbl, on 09 July 2011 - 07:05 AM, said:

Yes and no. Here we have a simple operation which is

balance -= withdraw;

so you can put it in the CheckingAccount and SavingAccount class.
But imageine that later on, after you have execute: balance -= withdraw; you'll have to:
- register the transaction in a log file
- produce a report for IRS if the withdraw is > 10,000
- update number of withdraw performed during that month
- produce stats for the bank officials on what is the average withdraw to see if larger bills should be put in atm
- send a status to police force because this account is monitored
- ...

you will reproduce the code for that in both subclasses ?


You're right of course, I was thinking of this simple example, and not of a full-scale banking system... which isn't a great way to design software. This thread has forced my brain to re-examine some of the fundamentals of deign I thought I had forgotten (and some I hadn't even realised I had learned :) ) - its been quite good, so I'm almost disappointed Shango has got it all working :P

Steve
Was This Post Helpful? 0
  • +
  • -

#28 shango11  Icon User is offline

  • D.I.C Head

Reputation: 3
  • View blog
  • Posts: 78
  • Joined: 06-July 11

Re: Overriding Methods

Posted 09 July 2011 - 12:00 AM

Thanks to kiwi-steve and pbl for all the amazing help!!
Here is the final code with some comments for future reference.
(I know its a lot of comments but my teacher requires me to make a lot of comments.)

Test program
import javax.swing.JOptionPane;

public class testAccount {
	
	/**
	 *The program asks the user for account information, type of account and operation they want to do.
	 *The program creates two types of account depending on what the user chooses, the savings account only allows him
	 *to withdraw the amount in his account while the checkings account has an overdraft of 500 (the user can withdraw past 0 up to -500)
	 * @param args
	 */
	
	//we create some of the variables that we are going to need during the program
	public static void main(String[] args) {
        boolean done = true;
        Account account1 = null;
        Account account2 = null;
        Account account3 = new Account();
        //we display the account toString and ask the user to choose an account type
        JOptionPane.showMessageDialog(null, "Your account information is: " + account3.toString());
        String accountTypeString = JOptionPane.showInputDialog(null, "           Choose an account type: \n" + "\n" + "1- Saving Account \n" + "\n" +
        		"2- Checking Account \n" + "\n");
        int accountType = Integer.parseInt(accountTypeString);
        
        //run loop to see if the user made a valid choice and then create the accounts accordingly
        if(accountType == 1){
        	account1 = new savingsAccount(1, 100, .045);
        }
        else if(accountType == 2){
        	account2 = new checkingAccounts(2, 100, .45);
        }
		else{
        	JOptionPane.showMessageDialog(null, "Invalid input");
        }
        
        //loop used for the savings account, it displays the user the account type, the balance and what they would like to do next
        if(accountType == 1){
        	while(done){
        		JOptionPane.showMessageDialog(null, "Your savings account info is: " + account1.toString() + "\n" + "Your balance is: " + account1.getBalance());
        		String savingsAccountActionsString = JOptionPane.showInputDialog( null, "           Choose an option: \n" + "\n" + "1- Withdraw \n" + "\n" + 
        				"2- Deposit \n" + "\n");
        		int savingsAccountActions = Integer.parseInt(savingsAccountActionsString);
        		//loop that checks what the user chose and passes the info to the account class which in turns passes it to the according subclass to do the transaction
        		if(savingsAccountActions == 1){
        			String savingsWithdrawAmountString = JOptionPane.showInputDialog(null, "Enter an amount to withdraw: ");
        			double savingsWithdrawAmount = Double.parseDouble(savingsWithdrawAmountString);
        			account1.withdraw(savingsWithdrawAmount);
        			JOptionPane.showMessageDialog(null, "Your balance is: " + account1.getBalance());
        			done = false;//comment this out for easier testing
        		}
        		else if(savingsAccountActions == 2){
        			String depositAmountString = JOptionPane.showInputDialog(null, "Enter an amount to deposit: ");
        			double depositAmount = Double.parseDouble(depositAmountString);
        			account1.deposit(depositAmount);
        			JOptionPane.showMessageDialog(null, "Your balance is: " + account1.getBalance());
        			done = false;//comment this out for easier testing
        		}
        	}
        }
        //loop used for the checkings account, it displays the user account type, the balance and what they would like to do next
        else if(accountType == 2){
        	JOptionPane.showMessageDialog(null, "Your checkings account info is: " + account2.toString() + "\n" + "Your balance is: " + account2.getBalance());
        	while(done){
        		String checkingsAccountActionString = JOptionPane.showInputDialog( null, "           Choose an option: \n" + "\n" + "1- Withdraw \n" + "\n" + 
        				"2- Deposit \n" + "\n");
        		int checkingsAccountAction = Integer.parseInt(checkingsAccountActionString);
        		//loop that checks what the user chose and passes the info to the account class which in turns passes it to the according subclass to do the transaction
        		if(checkingsAccountAction == 1){
        			String checkingsWithdrawAmountString = JOptionPane.showInputDialog(null, "Enter an amount to withdraw: ");
        			double checkingsWithdrawAmount = Double.parseDouble(checkingsWithdrawAmountString);
        			account2.withdraw(checkingsWithdrawAmount);
        			JOptionPane.showMessageDialog(null, "Your balance is: " + account2.getBalance());
        			done = false;//comment this out for easier testing
        		}
        		else if(checkingsAccountAction == 2){
        			String checkingsDepositAmountString = JOptionPane.showInputDialog(null, "Enter an amount to deposit: ");
        			double checkingsDepositAmount = Double.parseDouble(checkingsDepositAmountString);
        			account2.deposit(checkingsDepositAmount);
        			JOptionPane.showMessageDialog(null, "Your balance is: " + account2.getBalance());
        			done = false;//comment this out for easier testing
        		}
        	}
        }
        //used in case the user didnt choose an account type
        else{
        	JOptionPane.showMessageDialog(null, "Invalid choice");
        }
 }
}



Account class
import java.util.Date;

import javax.swing.JOptionPane;

/**
	The program uses a class with accesors and mutators to do a series
	of operation and return and basic output to the user.
	It has two subclasses that handles different accounts
	All info gets passed back to the testAccount.java
 */

//Create the class and define the variables needed
public class Account {
	protected int id;
	protected static double balance;
	protected double annualInterestRate;
	protected Date dateCreated;

	//Constructor with no arguments that creates a default account
	Account(){
		id = 0;
		balance = 0;
		//annualInterestRate = 0;
		//dateCreated = new Date();
	}
	
	//A constructor that takes in parameters and does a couple of operations.
	Account(int newId, double newBalance, double newAnnualInterestRate) {
		id = newId;
		balance = newBalance;
		//annualInterestRate = newAnnualInterestRate;
		//dateCreated = new Date();
	}
	//All the accesors used for the different variables
	public int getId() {
		return id;
	}
	public double getBalance() {
		return balance;
	}
	public double getAnnualInterestRate() {
		return annualInterestRate;
	}
	public Date getDateCreated() {
		return dateCreated;
	}
	
	//All the mutators used for the different variables
	public void setNewDate(Date newDate) {
		dateCreated = newDate;
	}
	public void setId(int newId) {
		id = newId;
	}
	public void setBalance(double newBalance) {
		balance = newBalance;
	}
	public void setAnnualInterestRate(double newAnnualInterestRate){
		annualInterestRate = newAnnualInterestRate;
	}
	
	//Method used to return the monthly rate and the monthly balance accordingly
	public static double getMonthlyInterestRate(double annualInterestRate) {
		double monthlyRate = 0;
		monthlyRate = annualInterestRate / 12;
		monthlyRate = monthlyRate * balance;
		return monthlyRate;
	}
	
	//Method used to withdraw money
	public void withdraw(double wd) {
		balance = balance - wd;
	}
	//Method used to deposit money
	public void deposit(double dp) {
		balance = balance + dp;
	}
	
	public String toString(){
		return "Account";
	}
}



Savings account class
import javax.swing.JOptionPane;

public class savingsAccount extends Account {
	
	/**
	 * If the user selects a savings account in the program and they want to withdraw/deposit
	 * all the checks for input and balance are made here, if nothing goes wrong the user
	 * is allowed to complete the transaction from the account class.
	 * @param newId
	 * @param newBalance
	 * @param newAnnualInterestRate
	 */
	
	savingsAccount(int newId, double newBalance, double newAnnualInterestRate) {
		super(newId, newBalance, newAnnualInterestRate);
	}

	//overrides the withdraw method from the account class and it also checks for invalid input
	//the user is only allowed to withdraw his balance and no more than that
	public void withdraw(double wd) {
		if(wd > balance){
			JOptionPane.showMessageDialog(null, "Insufficient funds");
			return;
		}
		else if(wd < 0){
			JOptionPane.showMessageDialog(null, "Incorrect input");
			return;
		}
		else{
		super.withdraw(wd);
	}
}
	//overrides the deposit method from the account class and it also checks for invalid input
	public void deposit(double dp){
		if(dp < 0){
			JOptionPane.showMessageDialog(null, "Incorrect input");
			return;
		}
		else{
			super.deposit(dp);
		}
	}
	
	//method used to override the toString in the account class
	public String toString(){
		return "Savings";
	}
}



Checkings accounts class
import javax.swing.JOptionPane;

public class checkingAccounts extends Account {
	
	/**
	 * If the user selects a checking account in the program and they want to withdraw/deposit
	 * all the checks for input and balance are made here, if nothing goes wrong the user
	 * is allowed to complete the transaction from the account class.
	 * @param newId
	 * @param newBalance
	 * @param newAnnualInterestRate
	 */
	
	checkingAccounts(int newId, double newBalance, double newAnnualInterestRate) {
		super(newId, newBalance, newAnnualInterestRate);
	}

	//overrides the withdraw method from the account class and it also checks for invalid input
	//the user is allowed to withdraw past 0 and up to -500 because of the overdraft check
	public void withdraw(double wd){
		if(wd > balance + 500) {
			JOptionPane.showMessageDialog(null, "Insufficient funds");
			return;
		}
		else if(wd < 0){
			JOptionPane.showMessageDialog(null, "Incorrect input");
			return;
		}
		else{
			super.withdraw(wd);
		}
	}
	
	//overrides the deposit method from the account class and it also checks for invalid input
	public void deposit(double dp){
		if(dp < 0){
			JOptionPane.showMessageDialog(null, "Incorrect input");
			return;
		}
		else{
			super.deposit(dp);
		}
	}
	
	//method used to override the toString in the account class
	public String toString(){
		return "Checkings";
	}
	
}


Was This Post Helpful? 0
  • +
  • -

#29 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8343
  • View blog
  • Posts: 31,890
  • Joined: 06-March 08

Re: Overriding Methods

Posted 09 July 2011 - 09:59 PM

No reason to have account1 and account2
you defeat the whole purpose of the exercise

While you are at it you could have done

SavingAccout account1;
CheckingAccount account2;

as you behave differently later on.

The whole purpose of the exercise was to have a

Account account;

put into it or a SavingAccount or a CheckingAccount
and continue the program with the main() program not knowing is account is a CheckingAccount or a SavingAccount

:^:
Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2