Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can somebody explain how this works?

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?

like image 654
sliucon13 Avatar asked Dec 28 '22 19:12

sliucon13


1 Answers

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.)

like image 147
Darien Avatar answered Jan 08 '23 04:01

Darien