【问题标题】:Can you tell me how this program is working?你能告诉我这个程序是如何工作的吗?
【发布时间】:2015-10-28 15:07:49
【问题描述】:

如果s1 指的是f1.switch() 创建的新对象,那么 (1)变量runningStatus如何传递给为内部类创建的新对象? (2) 变量runningStatus在内部类(s1引用)的对象中是如何变化的,体现在f1引用的Fan对象上?

interface Switch
{
    void on();
    void off();
}

class Fan
{
    private boolean runningStatus;
    public Switch getSwitch()
    {
        return new Switch()
        {
            public void on()
            {
                runningStatus = true;
            }
            public void off()
            {
                runningStatus = false;
            }
        };
    }
    public boolean getRunningStatus()
    {
        return runningStatus;
    }
}

class FanStatus
{
    public static void main(String[] args)
    {
        Fan f1 = new Fan();
        Switch s1 = f1.getSwitch();
        s1.on();
        System.out.println(f1.getRunningStatus());
        s1.off();
        System.out.println(f1.getRunningStatus());
    }
}

【问题讨论】:

  • 内部类可以访问其封闭的外部类实例变量。他们可以修改它们。
  • 试试Switch mySwitch = new Switch();。你会注意到你不能这样做,因为Switch 不是static class。由于它不是静态的,Switch 类基本上是Fan 内的“帮助器”或“容器”来组织您的代码。这就是 ergonaut 用f1.switch.runningStatus = true 表达的意思。

标签: java object instance inner-classes


【解决方案1】:
(1) How is variable runningStatus passed to the new object created for the inner class?

Fan 的 runningStatus 正在被 Switch 实例访问,它没有像参数一样被传递。

(2) How is change in variable runningStatus done in object of inner class (referred by s1), reflecting in the object of Fan referred by f1?

当 Switch 实例更改 Fan 实例中的变量时,它实际上是同一个变量。不是“按值传递”,也不是“按引用传递”,更像是:

f1.getSwitch().on() 

~ is equivalent to ~

f1.switch.runningStatus = true

【讨论】:

    【解决方案2】:
    1. 内部类与变量runningStatus 共享相同的范围,因此它对内部类可见。将内部类视为Fan 对象中的另一个变量。

    2. 方法getSwitch() 返回调用该方法时实例化的Switch 对象的引用。因此,对s1 进行任何更改意味着您实际上是在更改Fan 实例内的Switch 对象的属性,在本例中为f1,这实际上改变了f1 的属性。

    【讨论】:

      【解决方案3】:

      (1) 教程中的内部类实际上可以访问的所有变量都称为匿名类

      Java Tutorial

      (2)如(1)中提到的就是本地类或匿名类的属性访问外部类的所有变量

      Great Inner Outer classes explanation

      【讨论】: