How to call methods from an extended class? - java

public class Account {
double currentBalance;
Account(double currentBalance) {
this.currentBalance = currentBalance;
}
double getBalance() {
return(this.currentBalance);
}
void deposit(double amount) {
this.currentBalance += amount;
}
void withdraw(double amount) {
this.currentBalance -= amount;
}
public String toString() {
return("Your current account balance is: $" + this.currentBalance);
}
}
public class SavingsAccount extends Account {
double interestRate;
SavingsAccount(double interestRate, double amount) {
super(amount);
this.interestRate = interestRate;
}
void addInterest(double interestRate) {
this.currentBalance = this.currentBalance + (this.currentBalance * (interestRate / 100));
}
public String toString() {
return("Your current account balance is: $" + this.currentBalance + ". Your interest rate is: " + this.interestRate + "%");
}
}
public class AccountTester {
public static void main(String[] args) {
System.out.println("Welcome to the COMP 251 BANK");
Account[] acc = new Account[10];
acc[0] = new Account (100000); // initial amount of 100k
System.out.println(acc[0].toString());
acc[0].deposit(50000); //deposit 50k
System.out.println("Current balance after depositing is: " + "$" + acc[0].getBalance());
acc[0].withdraw(10000);
System.out.println("Current balance after withdrawing is: " + "$" + acc[0].getBalance());
System.out.println();
System.out.println("CHECKING ACCOUNT");
acc[1] = new CheckingAccount(10000,50000); //overdraft limit of 1000, initial amount of 50k
System.out.println(acc[1].toString());
acc[1].deposit(20000); //I dont know what to do about the chequeDeposit
System.out.println("Current balance after depositing is: " + "$" + acc[1].getBalance());
System.out.println();
System.out.println("SAVINGS ACCOUNT");
acc[2] = new SavingsAccount(10, 50000);
System.out.println(acc[2].toString());
acc[2].deposit(10000);
System.out.println("Current balance after depositing is: " + "$" + acc[2].getBalance());
acc[2].addInterest();
}
}
I'm still new to this so I'm sorry if this is a bad question but I tried playing around with each class and I still can't figure out how to use the addInterest method I created in the SavingsAccount class that extends the Account class. I tried SavingsAccount.addInterest but I get a static reference error. I thought acc[2].addInterest would work but it says its undefined for the type Account.

You need to cast acc[2] to SavingsAccount before calling the method.
((SavingsAccount) acc[2]).addInterest();
It is called downcasting and here is an explanation of it.

You're trying to invoke a child class' method, addInterest from a base class reference.
In fact, your array has been declared as an array of Account objects
Account[] acc = new Account[10];
This class does not offer the addIntereset method, even though your arr[2] contains a SavingAccount instance, Java in fact will only be able to know this at run-time. At compile time, your syntax must be compliant with the declared type (Account).
To work around this problem you have two solutions: creating a generic addInterest method in your base class which your child classes will override or cast your arr[2] to a SavingAccount instance.
With the first approach, you're offering an addInterest method from the base class, so whatever instance is going to call the method (an actual Account or a subtype), it will always be able to invoke it.
public class Account {
public void addInterest(double interest){
//Account implementation
}
}
public class SavingAccount {
#Overrride
public void addInterest(double interest){
//SavingAccount implementation
}
}
So, in your main you could type with no errors:
Account[] arr = new Account[10];
arr[0] = new Account();
arr[0].addInterest(5); //No error, dynamic dispatch will call Account's implementation
arr[1] = new SavingAccount();
arr[1].addInterest(10); //No error, dynamic dispatch will call SavingAccount's implementation
With the second approach instead, you need to make sure that what you're downcasting corresponds to the subtype of your casting.
//Randomly assigning to acc an Account instance or a SavingAccount instance
Account acc = Math.round(Math.random()) == 0 ? new Account() : new SavingAccount();
//Making sure to downcast acc to SavingAccount with the instanceof operator
if (acc instanceof SavingAccount){
SavingAccount savAcc = (SavingAccount) acc;
savAcc.addInterest(5);
}

Related

How can I use a variable from all similar objects in an if statement (Java)?

I am a beginner in Java and I hit a small snag.
I'm writing some code for an imaginary bank, and I want to include all the accounts' balance into one if statement. I made a double called accountBalance that I use for each account.
For example, Josie.accountBalance = 1200. Josie is an object for the BankAccounts type I created.
I want to make an if statement, so that if the account balance is above 1000, the bank sends a message warning the account about this issue, and it refunds everything above 1000$.
I could just do an if statement for every account I create, and write my code there, but I was wondering if there was a way to write an if statement that applied to all the BankAccounts type, without having to specify the names.
Thanks.
Here's the code that I wrote.
package learnJavaNew;
import java.util.ArrayList;
public class BankAccounts {
final static double defaultBalance = 50;
final static double maxBalance = 1000;
static double oldBalance;
static int employees;
static double bankMoney;
static double accountBalance;
static double newBalance;
public static void main(String[] args) {
// Josie's Bank Account
BankAccounts Josie = new BankAccounts();
Josie.depositMoney(0);
Josie.accountBalance = defaultBalance + newBalance;
System.out.println(Josie.accountBalance);
Josie.withdrawMoney(25.64);
Josie.accountBalance = defaultBalance + newBalance;
System.out.println(Josie.accountBalance);
// Dan's Bank Account
BankAccounts Dan = new BankAccounts();
Dan.depositMoney(1000);
Dan.accountBalance = defaultBalance + newBalance;
System.out.println(Dan.accountBalance);
Dan.withdrawMoney(5);
Dan.accountBalance = defaultBalance + newBalance;
System.out.println(Dan.accountBalance);
// Accounts List
ArrayList<BankAccounts> accounts = new ArrayList<BankAccounts>();
accounts.add(Josie);
accounts.add(Dan);
System.out.println(accounts);
// Max Balance
if(accountBalance >= maxBalance) {
System.out.println("You have reached the maximum balance for your bank account, which is " + maxBalance + "$.");
System.out.println("You cannot deposit more money into this account.");
oldBalance = accountBalance;
accountBalance = 1000;
System.out.println("You have been refunded " + (oldBalance - accountBalance));
}
// New Balance
System.out.println(Dan.accountBalance);
System.out.println(Josie.accountBalance);
}
public void depositMoney(double depositedMoney) {
newBalance = depositedMoney;
}
public void withdrawMoney(double withdrawnMoney) {
newBalance = newBalance - withdrawnMoney;
}
}
This kind of depends on the result you want. If the above code gives you the right result, then it's fine. However I would probably do something like this, and omit the loop and the list entirely.
public void depositMoney(double depositedMoney) {
if( depositedMoney + accountBalance > 1000 )
System.out.println( "Maximum exceeded, not processed" );
else
accountBalance += depositedMoney;
}
Notice here that I've changed the previous operation of depositedMoney, including the fact that the method never updated accountBalance.
To refund money over an amount, you might return a value indicating the amount refunded.
public double depositMoney(double depositedMoney) {
double refund = 0;
if( depositedMoney + accountBalance > 1000 ) {
refund = depositedMoney + accountBalance - 1000;
accountBalance = 1000;
System.out.println( "Maximum exceeded, refund " + refund );
}
else
accountBalance += depositedMoney;
return refund;
}
Also, you really should be using instance variables. Remove the static keyword.
double bankMoney;
double accountBalance;
double newBalance;
This might be made clearer by a different object model.
I would propose a BankAccount class (not "a BankAccounts class" -- that would mean that an object is "a BankAccounts", a jarring concept) and a Bank class.
class BankAccount {
private String owner;
private double balance;
BankAccount(String s, double b) { owner = s; balance = b; }
String owner() { return owner; }
double balance() { return balance; }
void deposit(double amount) { … like before … }
void withdraw(double amount) { … like before … }
}
and
class Bank {
static List<BankAccount> accounts = new ArrayList<>();
public static void main(String[] args) {
// set up some accounts
BankAccount josie = new BankAccount("Josie", 0);
accounts.add(josie);
BankAccount dan = new BankAccount("Dan", 1000);
accounts.add(dan);
:
etc
:
// print them all
double total = 0;
for (BankAccount acnt : accounts) {
System.out.printf("Account %s : balance %s %n",
acnt.owner(), acnt.balance());
total += acnt.balance();
}
System.out.printf("Total value of accounts: %s %n", total);
}
}
The benefit of this approach is that it makes it clearer what operations are for a single account and what operations are on "all accounts".

Java Bank Account Logic

I am trying to create a bank account class with few tools such as Balance, Deposit and withdrawal. I created super class and two sub class. One of the sub class(checking account) needs to charge a 10$ fee after 2 transactions.
I am having small trouble in the following program. It is a minor part of the program and I tried everything but I can not think of the solution. The problem is marked with star box comment in the code. The bank account (super Class) class is attached for your reference.
It is charging the transaction fee even though withdrawal is failed due to unavailability of enough balance. I understand why it is doing that but can someone suggest any solution?
//This is the sub Class "Checking Account"
public class CheckingAccount extends BankAccount
{
//Private Instance Variablea
private double dTransFee;
private int iFreeCheckPerMonth;
private int iNumChecks;
//Constructor
public CheckingAccount(String sName, int iAccountNumber)
{
super(sName, iAccountNumber);
dTransFee = 10;
iFreeCheckPerMonth = 2;
iNumChecks=0;
}
//Overriding method from the Bank Account Class
public boolean bWithdrawl (double dMoney)
{
if (iNumChecks<2)
{
super.bWithdrawl(dMoney);
iNumChecks++;
iFreeCheckPerMonth--;
}
else
{
/****************************
* I DON'T KNOW HOW I CAN MAKE STATEMENT SUCH AS
* IF BWITHDRAL IS FALSE(FAILS) DON'T TAKE OUT 10 FROM BALANCE.
***************************/
super.bWithdrawl(dMoney);
dBalance = dBalance- dTransFee;
iNumChecks++;
iFreeCheckPerMonth--;
}
return false;
}
//Prints how many checks are left
public int FreeChecksLeft ()
{
return iFreeCheckPerMonth;
}
//Prints how many checks have been used
public int CheckUsed ()
{
return iNumChecks;
}
}
//Super Class
/**************************************************************
*Name: BankAccount
*Input:Name and account number. Deposit and withdrawal amount for methods
*Output: None
*Description:
* Date: 10/19/2017 Author: Apurva Gandhi
**************************************************************/
public class BankAccount
{
//Private Instance Variable
protected double dBalance;
protected int iAccountNum;
protected String sOwnerName;
//Constructor
public BankAccount (String sName, int iAccountNumber)
{
iAccountNum = iAccountNumber;
sOwnerName = sName;
}
/**************************************************************
*Name: deposit
*Input:amount of money
*Output: none
*Description: takes the amount of money and add the amount to the balance.
* Date: 10/19/2017 Author: Apurva Gandhi
**************************************************************/
//Method for deposit
public void deposit(double dMoney)
{
dBalance += dMoney;
}
/**************************************************************
*Name: Withdrawal
*Input:amount of money
*Output: none
*Description: takes the amount of money and subtracts the amount from the balance.
* Date: 10/19/2017 Author: Apurva Gandhi
**************************************************************/
//Method for Withdrawal
public boolean bWithdrawl (double dMoney)
{
if (dMoney <= dBalance)
{
dBalance -= dMoney;
}
return false;
}
//Method to get balance
public double getBalance()
{
return dBalance;
}
}
//Here is the tester for Checking Account
public class CheckingTester
{
public static void main(String[] args)
{
//Create Checking account
CheckingAccount ca1 = new CheckingAccount ("Apurva", 1000);
//Make deposit
ca1.deposit(500);
//Verify that it worked
System.out.println("After deposit the balance is: " + ca1.getBalance()+" Expected:500");
//Check #1
//Test a withdrawal
ca1.bWithdrawl(100);
//Verify that it worked
System.out.println("After withdrawal the balance is : " + ca1.getBalance()+ " Expected 400");
//Checks the number of free checks available for use
ca1.FreeChecksLeft();
System.out.println("Number of Free Checks left are: "+ca1.FreeChecksLeft()+ " Expected 1");
//Check how many checks have been used
ca1.CheckUsed();
System.out.println("The number of check used are: "+ ca1.CheckUsed()+(" Expected 1"));
//Check #2
ca1.bWithdrawl(100);
System.out.println("After withdrawal the balance is : " + ca1.getBalance()+ " Expected 300");
//Check 3
ca1.bWithdrawl(100);
System.out.println("After withdrawal the balance is : " + ca1.getBalance()+ " Expected 190");
//Check 4
ca1.bWithdrawl(200);
System.out.println("After withdrawal the balance is : " + ca1.getBalance()+ " Expected 190");
}
}

Code returning node instead of value of subclass

I am very new to programming and am having a problem with some code for a class I am taking. I need to make a bank account class that returns the balance, adds a deposit, makes a withdrawal, and prints a statement with the current interest rate. I am stuck trying to get the the main class to return the values of the savings account class. Instead it returns the node value and I can't figure out what I a doing wrong. Any help would be appreciated. Code is below.
FinalExam.java
import java.io.*;
import java.util.Scanner;
public class FinalExam
{
SavingsAccount savings;
static String name;
static double balance;
public static void main (String[] args) throws NegativeAmountException, InsufficientFundsException {
double amount = 0;
SavingsAccount savings = null;
Scanner keyboard = new Scanner(System.in);
try
{
savings = new SavingsAccount("Penny Saved", 500.00, .05);
System.out.println(savings);
}
catch(NegativeAmountException e)
{
System.out.println("NegativeAmountException: " + e.getMessage());
System.exit(1);
}
System.out.println(savings);
Scanner input = new Scanner(System.in);
System.out.print("Enter your deposit amount: ");
amount = keyboard.nextDouble();
System.out.println(savings);
System.out.println("Enter your withdrawal amount: ");
amount = keyboard.nextDouble();
savings.postInterest();
System.out.println(savings);
}
}
BankAccount.java
import java.util.InputMismatchException;
import java.util.Scanner; //Import for scanner
public class BankAccount {
public String name;
public double balance;
//set name and balance
// make sure balance is not negative
// throw exception if balance is negative
public BankAccount(String name, double balance)throws NegativeAmountException {
if (balance < 0)
throw new NegativeAmountException("Cannot create a BankAccount with a negative balance");
}
public BankAccount(String name)
throws NegativeAmountException
{
// set name and use 0 balance
name = null;
balance = 0;
}
public void deposit(double amount) throws NegativeAmountException {
if (amount < 0)
throw new NegativeAmountException("Cannot deposit a negative amount: " + amount);
balance = balance + amount;
}
public void withdraw(double amount) throws InsufficientFundsException, NegativeAmountException {
if (amount > balance)
throw new InsufficientFundsException("Cannot withdraw more than the current balance of this BankAccount");
if (amount < 0)
throw new NegativeAmountException("Cannot withdraw a negative amount: " + amount);
balance = balance - amount;
}
public double getBalance() {
return balance;
}
// print bank statement including customer name
// and current account balance
public void printStatement() {
System.out.println("BankAccount owned by: " + name + " balance: $" + balance);
}
}
SavingsAcount.java
public class SavingsAccount extends BankAccount
{
double interest;
public SavingsAccount(String name, double balance, double interest) throws NegativeAmountException {
super(name, balance);
}
public double getInterest()
{
return interest;
}
public void postInterest() {
balance = balance + ((balance * interest)/12);
}
public void printStatement() {
super.printStatement();
System.out.println("Account for " + name + " Saved" + balance + " balance: $" + "Current Interest Rate is" + interest);
}
}
I know the last part of the FinalExam.java is incomplete, but I am trying to get the statement to print out before I move on the other issues. Any suggestions would be appreciated.
I am stuck trying to get the the main class to return the values of the savings account class. Instead it returns the node value and I can't figure out what I a doing wrong.
Your problem is that you are calling
savings = new SavingsAccount("Penny Saved", 500.00, .05);
System.out.println(savings);
println automatically calls the toString method on its argument. Since you didn't #Override the toString method of SavingsAccount, it prints what you call the "node value".
Your SavingsAccount has a method
public void printStatement()
which seems to print the information you want. So call it instead of println.
In the FinalExam.java class you suppose to print the values of the SavingsAccount.java class but you are getting the address. This id because in FinalExam.java class System.out.println(savings); rather than that yous should use like savings.printStatement();. May be I am not wrong what I guess..
When you print an object using System.out.println(savings) method, it internally calls the toString() method on that object. You need to implement the toString() method for both the classes SavingsAccount and BankAccount.
For the SavingsAccount use this:
#Override
public String toString() {
return "SavingsAccount{" +
super.toString() +
", interest=" + interest +
'}';
}
For BankAccount use this:
#Override
public String toString() {
return "BankAccount{" +
"name='" + name + '\'' +
", balance=" + balance +
'}';
}
Currently you are not setting the instance variables in the class. You are checking for negative balance and throwing the exception.
Also you need to improve the constructor in BankAccount class as follow:
public BankAccount(String name, double balance)throws NegativeAmountException {
if (balance < 0) {
throw new NegativeAmountException("Cannot create a BankAccount with a negative balance");
}
this.name = name;
this.balance = balance;
}
// Update the SavingsAccount class constructor as well
public SavingsAccount(String name, double balance, double interest) throws NegativeAmountException {
super(name, balance);
this.interest = interest; // this is missing in your code.
}
Other thing which I have observed it that, you are creating multiple instances of Scanner class. You can use the same keyboard instance every where in the main method. No need to create multiple instances. One of them is unnecessary.
Scanner keyboard = new Scanner(System.in);
Scanner input = new Scanner(System.in);
Answer is already given, but there is also problem in your BankAccount class constructors, you did not assign instance variable to constructor arguments, you just check constraint so,
public BankAccount(String name, double balance)throws NegativeAmountException {
if (balance < 0)
throw new NegativeAmountException("Cannot create a BankAccount with a negative balance");
this.name = name;
this.balance = balance;
}
and
public BankAccount(String name) {
// set name and use 0 balance
this.name = name;
this.balance = 0;
}
thanks:)

Java - add value to it to a variable from another class

My problem is how do I add a value to a variable from another class, for example:
private int balance;
then later in the methods in the same class, I add values to the balance with no problem using:
balance += 50;
but when I go to another class, and type the object then the setter for the balance:
myObject.setBalance(50);
but the problem strikes here, when I go to the first class and return the balance from there, i get nothing (or the old value of balance) in other words, the NEW value of balance is not being added. Any ideas why? I've been stuck at this point for the last couple of hours
Here's my code:
public class Zoo
{
private int balance;
public void setBalance(int balance)
{
this.balance = balance;
}
public int getBalance()
{
return this.balance;
}
}
MY SECOND CLASS:
public class RandomEvents
{
private Zoo ZooBalance = new Zoo();
public void callEventSix()
{
System.out.println("A local group has raised money to your Zoo");
System.out.println("Would you like to accept the money? (y) or (n)");
Scanner readerEventThree = new Scanner(System.in);
String readerTwo = readerEventThree.next();
if ( readerTwo.equals("y") )
{
ZooBalance.setBalance(166);
System.out.println("You have accepted the gift");
System.out.println("Your new balance is " + ZooBalance.getBalance());
} else if ( readerTwo.equals("n") )
{
System.out.println("You have refused the gift");
}
}
}
In your case
Replace this line:
ZooBalance.setBalance(166);
with:
ZooBalance.setBalance(ZooBalance.getBalance() + 166);
Sytem.out.println(ZooBalance.getBalance()); // 166
You need to make a setter for that class. Assuming the name of the class is TestClass.
class TestClass {
private int balance = 50;
};
public int getBalance() {
return this.balance;
};
public void setBalance(int newBalance) {
this.balance = newBalance;
};
And then in another class:
TestClass test = new TestClass();
test.setBalance(test.getBalance() + 50);
System.out.println(test.getBalance);// 100
I'm pretty sure there's a difference between adding 50 to a value and setting a value to 50.
myObject.setBalance(50); will not add 50, it will change the value to 50. To add 50, you'd have to do something along the lines of myObject.setBalance(myObject.getBalance() + 50);
generally there are two ways to this.
First. Use getter and setter:
Zoo zoo = new Zoo();
zoo.setBalance(zoo.getBalance() + 50);
Second. Add an adder method:
public void addToBalance(int addend) {
balance += addend;
}
Zoo zoo = new Zoo();
zoo.addToBalance(50);

adding static attribute to constructor attribute

The problem is the following:
(Savings Account Class) Create class SavingsAccount. Use a static
variable annualInterestRate to store the annual interest rate for all
account holders. Each object of the class contains a private instance
variable savingsBalance indicating the amount the saver currently has
on deposit. Provide method calculateMonthlyInterest to calculate the
monthly interest by multiplying the savingsBalance by
annualInterestRate divided by 12—this interest should be added to
savings- Balance. Provide a static method modifyInterestRate that sets
the annualInterestRate to a new value. Write a program to test class
SavingsAccount. Instantiate two savingsAccount objects, saver1 and
saver2, with balances of $2000.00 and $3000.00, respectively. Set
annualInterestRate to 4%, then calculate the monthly interest for each
of 12 months and print the new balances for both savers. Next, set the
annualInterestRate to 5%, calculate the next month’s interest and
print the new balances for both savers.
I solved it all, but the balance is not incrementing -- it is staying the same. It should increment with every change in annual interest rate (at least, that's what I understood).
class SavingsAccount
{
static double annualInterestRate;
private double savingsBalance;
public SavingsAccount(double balance)
{
savingsBalance = balance;
}
public double calculateMonthlyInterest()
{
return (savingsBalance*annualInterestRate)/12;
}
public static void modifyInterestRate(double rate)
{
annualInterestRate = rate;
}
public static double getannualInterestRate(){return annualInterestRate;}
public double getsavingsBalance(){return savingsBalance;}
}
public class SavingsTest
{
public static void main(String args[])
{
SavingsAccount saver1 = new SavingsAccount(2000.0);
SavingsAccount saver2 = new SavingsAccount(3000.0);
SavingsAccount.modifyInterestRate(4);
System.out.printf("Balance for Saver1 = %.2f\nBalance for Saver2 = %.2f\nInterest Rate = %.2f\n\n",saver1.getsavingsBalance()+saver1.calculateMonthlyInterest(),saver2.getsavingsBalance(),SavingsAccount.getannualInterestRate());
SavingsAccount.modifyInterestRate(5);
System.out.printf("New Balance for Saver1 = %.2f\nNew Balance for Saver2 = %.2f\nInterest Rate = %.2f\n\n",saver1.getsavingsBalance(),saver2.getsavingsBalance(),SavingsAccount.getannualInterestRate());
}
}
You are not modifying the value of savingsBalance in this code.
public double addMonthlyInterest() {
savingsBalance += (savingsBalance*annualInterestRate)/12;
return savingBalance;
}
This will return the new balance and 'increment'
In your first print statement, for the first argument you are calculating the balance after calculating the monthly interest and adding them together and didn't set the new value as the value of the class member savingsBalance.
In your second print statement, since you did not set the calculated value back to the class member through a setter, it is simply printing out the original value that the classes were instantiated with.
On a side note, don't do inline calculations in print statements. They are confusing and not easy to read for anyone. A good way is to initialize local members in the method and using them for calculations and printing the local members.
Just wanted to share my answer.
public class SavingsAccount {
private static float annualInterestRate = 0f;
private float savingsBalance;
public SavingsAccount(float balance) {
savingsBalance = balance;
}
public static void setAnnualInterestRate(float t) {
if (t >= 0 && t <= 1)
annualInterestRate = t;
else
throw new IllegalArgumentException("Annual interest rate should be between 0 and 1");
}
private float calculateMonthlyInterest() {
return savingsBalance * annualInterestRate / 12;
}
public float getSavingsBalance() {
return savingsBalance + calculateMonthlyInterest();
}
public float getAnnualInterestRate(){
return annualInterestRate;
}
public String toString() {
return String.format("Balance: %.2f", getSavingsBalance());
}
}
in main
SavingsAccount s1 = new SavingsAccount(2000);
SavingsAccount s2 = new SavingsAccount(3000);
SavingsAccount.setAnnualInterestRate(0.04f);
System.out.println("S1: " + s1);
System.out.println("S2: " + s2);
SavingsAccount.setAnnualInterestRate(0.05f);
System.out.println("S1: " + s1);
System.out.println("S2: " + s2);

Categories