简体   繁体   English

Java 从子类访问受保护的变量

[英]Java access protected variable from subclass

I am working on a homework assignment looking at inheritance in java. I am having a little trouble understand how to access an array in the superclass from the subclass.我正在做一项家庭作业,查看 java 中的 inheritance。我在理解如何从子类访问超类中的数组时遇到了一些麻烦。 I looked at several other questions, and since I am so new to java, I'm still just not quite getting it.我查看了其他几个问题,由于我对 java 还很陌生,所以我还是不太明白。

Here is the super class这里是超级 class

import java.text.NumberFormat;

/**
 * Bank represents a single Bank containing a number of BankAccounts.
 */
public class Bank {

    // Member variables:

    /** The array of BankAccount objects contained in this bank. */
    protected BankAccount[] myAccounts = new BankAccount[2000];

    /** The number of BankAccount objects stored in the array in this bank. */
    protected int numberOfAccounts = 0;


    // Constructors:

    /**
     * Creates a Bank.
     */
    public Bank() {}


    // Methods:

    /** 
     * Creates an account with the name and balance, and adds it to 
     * the bank's list of accounts.
     * If the name already exists, no account will be created.
     * @param aName The name for the new account.
     * @param aBalance The initial balance for the new account.
     */
    public void createAccount( String aName, double aBalance) {
        BankAccount existing = this.findAccount( aName);
        if( existing != null) return;
        BankAccount anAccount = new BankAccount( aBalance, aName);
        this.myAccounts[ numberOfAccounts] = anAccount;
        this.numberOfAccounts++;
    }

    /** 
     * Finds an account in the bank's list of accounts by name.
     * If no account is found, this method returns null.
     * @param aName The name of the BankAccount to search for.
     * @return The BankAccount bearing the given name, if found.
     */
    public BankAccount findAccount( String aName) {
        BankAccount answer = null;
        for( int index = 0; index < numberOfAccounts; index++) {
            BankAccount anAccount = this.myAccounts[ index];
            if( aName.equals( anAccount.getName())) {
                return( anAccount);
            }
        }
        return( answer);
    }

    /** 
     * Returns a String which represents a short summary of 
     * all the accounts in the bank.
     * @return A String representation of all accounts and their balances in the bank.
     */
    public String toString() {
        String answer = "";
        NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance();
        for( int index = 0; index < numberOfAccounts; index++) {
            BankAccount anAccount = this.myAccounts[ index];
            String money = currencyFormatter.format( anAccount.getBalance());
            answer += anAccount.getName() + " \t" + money + "\n";
        }
        return( answer);
    }

}

and here is the start of the subclass这是子类的开始

public class BankSubClass extends Bank{
    private double interestPaid;

    // Constructor
    public BankSubClass(String aName, double aBalance, double aInterest) {
        super();
        this.interestPaid = aInterest;
    }

    // Getters
    public double getInterestPaid() {return(this.interestPaid);}

    // Setters
    public void setInterestPaid(double setInterestPaid) {this.interestPaid = setInterestPaid;}

    // Other methods
    public double endOfYear() {
        for (i=0;i<BankAccount.length();i++) {

        }
    }

}

That for loop at the end are where things are getting a little tripped up.最后的 for 循环是事情变得有点绊倒的地方。 Netbeans is throwing up errors saying "cannot find symbol: variable i". Netbeans 抛出错误“找不到符号:变量 i”。 Maybe this has nothing to do with the bank account array I'm trying to use, I don't know.也许这与我尝试使用的银行帐户数组无关,我不知道。 Any help is much appreciated任何帮助深表感谢

Thanks for your time!谢谢你的时间!

edit编辑

So here is a continuation of the same homework所以这是相同作业的延续

Thanks for the replies everyone, your suggestions took care of that problem, I am currently hitting another speed bump at the moment however.感谢大家的回复,您的建议解决了这个问题,但是我目前正在遇到另一个减速带。 The idea behind this method that the for loop is in is to run through the array of BankAccount objects, check to see if any of them are of the InterestAccount type (a class I previously built) and if they are, call the yearlyUpdate() method from that class for 循环所在方法背后的想法是遍历 BankAccount 对象数组,检查它们是否属于 InterestAccount 类型(我之前构建的 class),如果是,则调用 yearlyUpdate()来自 class 的方法

Here is the InterestAccount class这是 InterestAccount class

public class InterestAccount extends BankAccount {
    private double interestRate;

    // Constructor
    /**
     * Create and interest bearing bank account with a balance, name,
     * and interest rate
     * @param aBalance The balance of the account
     * @param aName The name tied to the account
     * @param myInterestRate The interest rate of the account
     */
    public InterestAccount(double aBalance, String aName, double myInterestRate) {
        super(aBalance, aName);
        this.interestRate = myInterestRate;
    }

    // Getters
    /**
     * Gets the interest rate of the account
     * @return the interest rate of the account
     */
    public double getInterestRate() {return(this.interestRate);}

    // Setters
    /**
     * Sets the interest rate of the account
     * @param interestSet The new interest rate of the account
     */
    public void setInterestRate(int interestSet) {this.interestRate = interestSet;}

    // Other Methods
    /**
     * Calculates the interest earned on the account over a year
     * @return the interest earned over a year
     */
    public double yearlyUpdate() {
        double answer = (super.getBalance()*this.interestRate);
        return answer;
    }
}

Here is the super class I am currently working with这是我目前正在使用的超级 class

import java.text.NumberFormat;

/**
 * Bank represents a single Bank containing a number of BankAccounts.
 */
public class Bank {

    // Member variables:

    /** The array of BankAccount objects contained in this bank. */
    protected BankAccount[] myAccounts = new BankAccount[2000];

    /** The number of BankAccount objects stored in the array in this bank. */
    protected int numberOfAccounts = 0;


    // Constructors:

    /**
     * Creates a Bank.
     */
    public Bank() {}


    // Methods:

    /** 
     * Creates an account with the name and balance, and adds it to 
     * the bank's list of accounts.
     * If the name already exists, no account will be created.
     * @param aName The name for the new account.
     * @param aBalance The initial balance for the new account.
     */
    public void createAccount( String aName, double aBalance) {
        BankAccount existing = this.findAccount( aName);
        if( existing != null) return;
        BankAccount anAccount = new BankAccount( aBalance, aName);
        this.myAccounts[ numberOfAccounts] = anAccount;
        this.numberOfAccounts++;
    }

    /** 
     * Finds an account in the bank's list of accounts by name.
     * If no account is found, this method returns null.
     * @param aName The name of the BankAccount to search for.
     * @return The BankAccount bearing the given name, if found.
     */
    public BankAccount findAccount( String aName) {
        BankAccount answer = null;
        for( int index = 0; index < numberOfAccounts; index++) {
            BankAccount anAccount = this.myAccounts[ index];
            if( aName.equals( anAccount.getName())) {
                return( anAccount);
            }
        }
        return( answer);
    }

    /** 
     * Returns a String which represents a short summary of 
     * all the accounts in the bank.
     * @return A String representation of all accounts and their balances in the bank.
     */
    public String toString() {
        String answer = "";
        NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance();
        for( int index = 0; index < numberOfAccounts; index++) {
            BankAccount anAccount = this.myAccounts[ index];
            String money = currencyFormatter.format( anAccount.getBalance());
            answer += anAccount.getName() + " \t" + money + "\n";
        }
        return( answer);
    }

}

And finally, here is the subclass in which I am trying to run this for loop最后,这是我试图在其中运行此 for 循环的子类

public class BankSubClass extends Bank{
    private double interestPaid;

    // Constructor
    public BankSubClass(String aName, double aBalance, double aInterest) {
        super();
        this.interestPaid = aInterest;
    }

    // Getters
    public double getInterestPaid() {return(this.interestPaid);}

    // Setters
    public void setInterestPaid(double setInterestPaid) {this.interestPaid = setInterestPaid;}

    // Other methods
    public double endOfYear() {
        double trackInterest=0;
        for (int i=0;i<numberOfAccounts;i++) {
            BankAccount working = myAccounts[i];
            boolean hasInterest = working instanceof InterestAccount;
            if (hasInterest) {
                trackInterest = trackInterest + working.yearlyUpdate();
            }
            return trackInterest;
        }
    }

}

currently.netbeans can't find the "yearlyUpdate()" method when attempting to call it on "working" what I'm not understanding is since the previous code verified that the working object was of the InterestAccount type, it should have that method available currently.netbeans 在尝试在“工作”时调用它时找不到“yearlyUpdate()”方法我不理解的是,因为前面的代码验证了工作 object 是 InterestAccount 类型,它应该有那个方法可用的

Thanks for the help!谢谢您的帮助!

// Other methods
public double endOfYear() {
    for (i=0;i<BankAccount.length();i++) {

    }
}

You need to declare i你需要声明i

// Other methods
public double endOfYear() {
    for (int i=0;i<BankAccount.length();i++) {

    }
}

Like the error says: i is undefined.就像错误所说:我是未定义的。

try:尝试:

for (int i=0;i<BankAccount.length();i++)

I'm guessing that is still bad since you want the length of the array, not the BankAccount class (which may be undefined)我猜这仍然很糟糕,因为你想要数组的长度,而不是 BankAccount class(可能未定义)

for (int i=0;i<myAccounts.length();i++)

For the error, you need to define the variable i before using it in BankSubClass.endOfYear.对于错误,您需要在 BankSubClass.endOfYear 中使用它之前定义变量 i。 The statement should be声明应该是

for (int i=0;i<BankAccount.length();i++)

You didn't declare i in side the for loop你没有在 for 循环中声明i

for (int i=0;i<BankAccount.length();i++)

In your loop, variable i is undeclared.在您的循环中,变量i未声明。 Also, since I think you wish to loop through the accounts in the array, I think you should be using the following:此外,由于我认为您希望遍历数组中的帐户,因此我认为您应该使用以下内容:

for(int i = 0; < numberOfAccounts; i++)
{
    BankAccount bankAccount = myAccounts[i];
    // other stuff
}

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

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