Mr. Meeshmew
Mr. Meeshmew

Reputation: 11

How do i call a method of a subclass when referencing its superclass?

when ever i try compliling it says the writeCheck method does not exist and i know it has to do with i am calling the method, by is there a way to call a method from the Checkings class when using Account types? My hashmap has different account types and i only want to be able to write a check if the account specified is a checking account. I have that check system implemented, but i still don't know how to access the subclass's methods.

import java.util.HashMap;
import java.util.Map;
import java.util.Random;
public class Person
{
public final String name,address,phoneNumber;
public Random aNumGen;
public HashMap<Integer,Account> accounts;
public Integer accountNum;
public Person(String name,String address,String phoneNumber)
{
    aNumGen=new Random();
    accounts = new HashMap<Integer,Account>();
    this.name=name;
    this.address=address;
    this.phoneNumber=phoneNumber;
}
public void addAccount(String accountType,double initialAmount,Integer numberOfYears)
{
    do
    {
        accountNum = aNumGen.nextInt(999999);
    }
    while(accounts.containsKey(accountNum));

    if(accountType.toLowerCase().contains("check"))
    {
        accounts.put(accountNum,new Checkings(name,address,phoneNumber,accountNum));
        deposit(accountNum,initialAmount);
    }
    else if(accountType.toLowerCase().contains("sav"))
    {
        accounts.put(accountNum,new Savings(name,address,phoneNumber,accountNum));
        deposit(accountNum,initialAmount);
    }
    else if(accountType.toLowerCase().contains("loan"))
    {
        accounts.put(accountNum,new HomeLoan(name,address,phoneNumber,accountNum,initialAmount,numberOfYears));
    }
    else
    {
      System.out.println("That account type does not exist.");  
    }
    printAccounts();
}

public void printAccounts()
{
    System.out.println(name +"  " + address + " " + phoneNumber);
    for(Map.Entry<Integer,Account> account: accounts.entrySet())
    {
        System.out.println("    " + account.getValue().getType()+ ": " + account.getKey() + "  " + "$" + account.getValue().getBalance());
    }
    System.out.println();
}

this is where I am having trouble. This is still part of the person class.

public void writeCheck(Integer accountNumber, String toPerson, Integer amount)
{
    if(accounts.containsKey(accountNumber) && accounts.get(accountNumber).getType().equalsIgnoreCase("Checkings"))
    {
        accounts.get(accountNumber).writeCheck(toPerson, amount);
    }
}

}

Account superclass.

public class Account
{
public double balance;
public final int accountNumber;
public String name, address, phoneNumber,type;

public Account(String name, String address, String phoneNumber, int accountNumber)
{
    this.name = name;
    this.address = address;
    this.phoneNumber = phoneNumber;
    this.accountNumber = accountNumber;

}


public int getAccountNumber()
{
    return accountNumber;
}

public void deposit(double amount)
{
    balance += amount;
}
public void withdrawl(double amount)
{
    if(amount <= balance)
    {
        balance-=amount;
    }
}
public String getType()
{
    return type;
}
public void closeAccount()
{
    balance=0;
    System.out.println("Your account has been closed.");
}

} subclass Checkings

import java.util.HashMap;
import java.util.Map;
public class Checkings extends Account
{
public HashMap<String,Integer> checkHistory;

public Checkings(String name, String address, String phoneNumber, int accountNumber)
{
    super(name, address, phoneNumber, accountNumber);
    checkHistory = new HashMap<String,Integer>();
    type = "Checkings";
}
public void writeCheck(String toAccount, Integer amount)
{
    withdrawl(amount);
    checkHistory.put(toAccount, amount);
}
public void viewCheckHistory()
{
    System.out.println("Account: " + getAccountNumber());
    for(Map.Entry<String,Integer> check: checkHistory.entrySet())
    {
        System.out.println("To: " + check.getKey() + " Amount: " + check.getValue());
    }
}

}

Upvotes: 0

Views: 312

Answers (3)

PapaFreud
PapaFreud

Reputation: 3878

If you have a variable of the Account type, it doesn't have the writeCheck method, even if the actual instance is a Checkings. So what you need to do is cast it to the correct subclass - which will only work if it really is the right subclass type:

Account a = new Checkings(...); // this is ok
a.writeCheck(...); // you can't do this

// cast to subtype
Checkings checkingsAccount = (Checkings) a;

checkingsAccount.writeCheck(...); // this should work

A better way might be to have a method with the same signature but with different code for all Account types, something like

(in Account)

abstract class Account {
    abstract void makePayment(String accountNumber, int amount);
}

(in Checkings)

class Checkings extends Account {

    void makePayment(String accountNumber, int amount){
        // this is a checkings account, so put the "writeCheck" code here
    }
}

That way, you don't have to cast or even care about what account type you're working on, you just do this:

Account a = new Checkings(...); // or any Account subclass
a.makePayment(accountNumber, amount);

You probably should be checking for errors though - such as making sure there really is an account with that number, that there's enough cash or credit in the account, etc. But I suppose this is not really a real-life financial system.

Upvotes: 2

Vineet Kosaraju
Vineet Kosaraju

Reputation: 5840

If you have the following, where ClassB extends ClassA

ClassA obj = new ClassB(); 

Then to call B's method which A does not have, casting is required.

ClassB newObj = (ClassB) obj;

Upvotes: 0

Trompetas Rouketas
Trompetas Rouketas

Reputation: 96

I believe you'd solve your problem if you used instanceOf. You can look it up here

Upvotes: 0

Related Questions