sli*_*n13 4 java swing scope initializing
我有这行代码.
class ButtonPanel extends JPanel implements ActionListener
{
public ButtonPanel()
{
yellowButton = new JButton("Yellow");
Run Code Online (Sandbox Code Playgroud)
它工作,我认为Java在创建像这样的jButton实例之前需要知道yellowButton的类型?
JButton yellowButton = new JButton("Yellow");
Run Code Online (Sandbox Code Playgroud)
谁能解释一下这是如何工作的?
如果它真的有用,那么这意味着yellowButton你可能没有注意到的类字段.
再次检查课程.你可能拥有的是更像这样的东西:
class ButtonPanel extends JPanel implements ActionListener
{
private JButton yellowButton;
public ButtonPanel()
{
yellowButton = new JButton("Yellow");
/* this.yellowButton == yellowButton */
/* etc */
}
}
Run Code Online (Sandbox Code Playgroud)
如果foo在方法范围中找不到变量,它会自动回退到this.foo.相比之下,像PHP这样的语言没有这种灵活性.(对于PHP,您始终必须执行$this->foo而不是$foo访问类字段.)