Can someone 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 should know the yellowButton type before creating a jButton instance like this?

 JButton yellowButton = new JButton("Yellow"); 

can someone explain how this works?

+4
source share
2 answers

If this really works, then yellowButton is probably a class field that you have not noticed.

Check out the class again. You probably have something more:

 class ButtonPanel extends JPanel implements ActionListener { private JButton yellowButton; public ButtonPanel() { yellowButton = new JButton("Yellow"); /* this.yellowButton == yellowButton */ /* etc */ } } 

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

+9
source

It should not work, you always need to declare a variable type. Are you sure there is not enough code somewhere?

Like this in the beginning.

 private JButton yellowButton = null; 
+1
source

All Articles