繁体   English   中英

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

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

什么时候我尝试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());
    }
}

}

如果您有一个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);

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

如果你使用了instanceOf我相信你会解决你的问题。 你可以在这里查找

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

ClassA obj = new ClassB(); 

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

ClassB newObj = (ClassB) obj;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM