4

我有这行代码。

class ButtonPanel extends JPanel implements ActionListener
{  
    public ButtonPanel()
    {  
        yellowButton = new JButton("Yellow");

它有效,我认为Java需要在创建这样的jButton实例之前知道yellowButton的类型?

JButton yellowButton = new JButton("Yellow");

有人可以解释这是如何工作的吗?

4

2 回答 2

9

如果它确实有效,那么这意味着yellowButton可能是您没有注意到的类字段。

再次检查班级。您可能拥有的更像是这样的:

class ButtonPanel extends JPanel implements ActionListener
{  
    private JButton yellowButton;

    public ButtonPanel()
    {  
        yellowButton = new JButton("Yellow");
        /* this.yellowButton == yellowButton */

        /* etc */
    }
}

foo如果在方法范围内找不到变量,它会自动回退到this.foo. 相比之下,像 PHP 这样的一些语言没有这种灵活性。(对于 PHP,您总是必须做$this->foo而不是$foo访问类字段。)

于 2011-06-10T18:39:57.090 回答
1

它不应该工作,您总是需要声明变量的类型。你确定你没有在某处遗漏一段代码吗?

一开始就这样。

private JButton yellowButton = null;
于 2011-06-10T18:39:51.637 回答