Alvin3001
Alvin3001

Reputation: 109

Can you tell me how this program is working?

If s1 is referring to the new object created by f1.switch(), then (1) How is variable runningStatus passed to the new object created for the inner class? (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?

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());
    }
}

Upvotes: 2

Views: 93

Answers (3)

JPRLCol
JPRLCol

Reputation: 200

(1) All the variables can be accessed by the inner Class actually in the tutorial is knows as anonymous class

Java Tutorial

(2) As mentioned in the (1) is the property of the local class or anonymous class access all the variables of the outer class

Great Inner Outer classes explanation

Upvotes: 0

Ahmed Shariff
Ahmed Shariff

Reputation: 793

  1. The inner class shares the same scope as the variable runningStatus, hence it is visible to the inner class. Think of the inner class as another variable within the Fan object.

  2. The method getSwitch() returns the reference of the Switch object instantiated when the method was called. hence making any changes to s1 means you are actually changing the properties of the Switch object inside the instance of Fan, in this case f1, which effectively alters the properties of f1.

Upvotes: 0

ergonaut
ergonaut

Reputation: 7057

(1) How is variable runningStatus passed to the new object created for the inner class?

Fan's runningStatus is being accessed by the Switch instance, it's not being passed like a parameter.

(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?

When the Switch instance changes the variable from Fan's instance, it's actually the same variable. It's not "passed by value", or "passed by reference", it's more like:

f1.getSwitch().on() 

~ is equivalent to ~

f1.switch.runningStatus = true

Upvotes: 4

Related Questions