Reputation: 109
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
Reputation: 200
(1) All the variables can be accessed by the inner Class actually in the tutorial is knows as anonymous class
(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
Reputation: 793
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.
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
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