can somebody explain how this works?

妖精的绣舞 提交于 2019-12-10 15:13:49

问题


I have this line of code.

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

and It works, I thought Java needs to know the type of yellowButton before creating an instance of a jButton like this?

JButton yellowButton = new JButton("Yellow");

can somebody explain how this works?


回答1:


If it really does work, then that means yellowButton is probably a class field that you didn't notice.

Check the class again. What you probably have is something more like this:

class ButtonPanel extends JPanel implements ActionListener
{  
    private JButton yellowButton;

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

        /* etc */
    }
}

If a variable foo cannot be found in a method scope, it automatically falls back to this.foo. In contrast, some languages like PHP do not have this flexibility. (For PHP you always have to do $this->foo instead of $foo to access class fields.)




回答2:


It shouldn't work, You always need to declare the type of your variable. Are you sure you not missing a piece of code somewhere?

Like this at the beggining.

private JButton yellowButton = null;


来源:https://stackoverflow.com/questions/6310649/can-somebody-explain-how-this-works

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!