i have some code in Ruby here below:
class A
@@lock = Monitor.new
class B
def method
@@lock.synchronize
puts "xxxxx"
end
end
end
end
after running it throws an error which said that below:
uninitialized class variable @@lock in A::B (NameError)
if i want to know how to access the outer class A's class variable @@lock from inner class B's method, how to do it? thank you in advance.
Java inner class is associated with the object of the class and they can access all the variables and methods of the outer class.
An instance of InnerClass can exist only within an instance of OuterClass and has direct access to the methods and fields of its enclosing instance. To instantiate an inner class, you must first instantiate the outer class.
Conclusion. Outer classes can access inner class private members in Java until a non-static member accesses it from a static context or an inaccessible scope. Inner classes can access the variables of the outer class, including the private instance variables.
Ruby Class VariablesClass variables begin with @@ and must be initialized before they can be used in method definitions. Referencing an uninitialized class variable produces an error. Class variables are shared among descendants of the class or module in which the class variables are defined.
I don't think you can without defining an accessor.
Class B
is lexically scoped inside of A, so its real name is A::B and various other things are different.
But it's not a child or any other sort of derived class, so it doesn't actually have any special rights to see private or protected or otherwise local elements of A.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With