从另一个类访问创建的对象

时间:2015-12-01 20:39:41

标签: java

对于作业,我被要求从主类中分离出一个嵌套类。

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
/**
 This program displays the growth of an investment.
*/
public class InvestmentViewer2
{ public static void main(String[] args)
 {
 JFrame frame = new JFrame();
 // The button to trigger the calculation
 JButton button = new JButton("Add Interest");
 // The application adds interest to this bank account
 final BankAccount account = new BankAccount(INITIAL_BALANCE);
 // The label for displaying the results
 final JLabel label = new JLabel("balance: " + account.getBalance());
 // The panel that holds the user interface components
 JPanel panel = new JPanel();
 panel.add(button);
 panel.add(label);
 frame.add(panel);

 class AddInterestListener implements ActionListener
 {
 public void actionPerformed(ActionEvent event)
 {
 double interest = account.getBalance()
 * INTEREST_RATE / 100;
 account.deposit(interest);
 label.setText(
 "balance: " + account.getBalance());
 }
 }
 ActionListener listener = new AddInterestListener();
 button.addActionListener(listener);
 frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 frame.setVisible(true);
 }
 private static final double INTEREST_RATE = 10;
 private static final double INITIAL_BALANCE = 1000;
 private static final int FRAME_WIDTH = 400;
 private static final int FRAME_HEIGHT = 100;
}

我将类AddInterestListener从主类中取出,并将其放在一个新文件中。现在,account.getBalance()不再起作用了。我找不到如何让新类AddInterestListener定位在主类中创建的帐户对象。

我还有一个简单的BankAccount类来创建对象。这有2个方法存放(双x)和getBalance()。

有关于作业问题的提示:存储参考文献 银行账户。将构造函数添加到设置引用的侦听器类。

我不明白他们在说什么。我试过扩展课程然后使用super。达到这个方法,但我被卡住了。

1 个答案:

答案 0 :(得分:1)

您需要在AddInterestListener上创建一个构造函数,将Account对象作为参数传入并将其存储在AddInterestListener类的字段中...

public class AddInterestListener implements ActionListener {
     private final Account account;

     public AddInterestListener(final Account account) {
         this.account = account;
     }

     public void actionPerformed(Event e) {
      ...
          account.deposit(interest);
      ...
     }
}