在引用其超类时如何调用子类的方法?

时间:2013-11-13 06:34:18

标签: java inheritance subclass

当我尝试compliling它说writeCheck方法不存在,我知道它与我调用方法有关,有没有办法在使用帐户类型时从Checkings类调用方法?我的hashmap有不同的帐户类型,我只希望能够写一个支票,如果指定的帐户是支票帐户。我已经实现了该检查系统,但我仍然不知道如何访问子类的方法。

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();
}

这是我遇到麻烦的地方。这仍然是人类的一部分。

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);
    }
}

}

帐户超类。

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.");
}

} 子类检查

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());
    }
}

}

3 个答案:

答案 0 :(得分:2)

如果您有一个Account类型的变量,它就没有writeCheck方法,即使实际的实例是Checkings。所以你需要做的是将它转换为正确的子类 - 只有当它真的是正确的子类类型时才会起作用:

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

更好的方法可能是使用相同签名但所有帐户类型具有不同代码的方法,例如

(在帐户中)

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

(在检查中)

class Checkings extends Account {

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

通过这种方式,您无需投射甚至关心您正在使用的帐户类型,只需这样做:

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

你可能应该检查错误 - 例如确保确实有一个帐号有这个号码,账号中有足够的现金或信用等等。但我想这不是真正的现实金融系统

答案 1 :(得分:0)

如果您使用instanceOf,我相信您可以解决您的问题。您可以查找here

答案 2 :(得分:0)

如果您有以下内容,ClassB extends ClassA

ClassA obj = new ClassB(); 

然后调用A没有的B方法,需要进行转换。

ClassB newObj = (ClassB) obj;