4

このコード行があります。

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

このようにjButtonのインスタンスを作成する前に、Javaは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 に答える