有人可以解释这是如何工作的吗? [英] can somebody explain how this works?
问题描述
我有这行代码.
class ButtonPanel extends JPanel implements ActionListener
{
public ButtonPanel()
{
yellowButton = new JButton("Yellow");
它有效,我认为Java在创建这样的jButton实例之前需要知道yellowButton的类型?
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?
推荐答案
如果它真的有效,那么这意味着 yellowButton
可能是一个你没有注意到的类字段.
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 */
}
}
如果在方法作用域中找不到变量 foo
,它会自动回退到 this.foo
.相比之下,像 PHP 这样的一些语言没有这种灵活性.(对于 PHP,您总是必须执行 $this->foo
而不是 $foo
来访问类字段.)
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.)
这篇关于有人可以解释这是如何工作的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!