你能告诉我这个程序是如何工作的吗?

Can you tell me how this program is working?

如果s1指的是f1.switch()创建的新对象,那么 (1) 变量runningStatus如何传递给为内部class创建的新对象? (2) 内部对象class(s1 引用)中变量runningStatus 的变化如何反映在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());
    }
}
(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实例的变量时,实际上是同一个变量。不是"passed by value",也不是"passed by reference",更像是:

f1.getSwitch().on() 

~ is equivalent to ~

f1.switch.runningStatus = true
  1. 内部class与变量runningStatus共享相同的作用域,因此对内部class可见。将内部 class 视为 Fan 对象中的另一个变量。

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

(1) 所有变量都可以通过内部 Class 访问,实际上在教程中被称为匿名 class

Java Tutorial

(2) 如(1)中提到的是属性的局部class或匿名class访问外部的所有变量class

Great Inner Outer classes explanation