What's the difference between Nested
and Child
in the example below? Is it just different syntax for the same thing?
class Parent
class Nested
...
end
end
class Child < Parent
...
end
A nested class is a member of its enclosing class. Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private. Static nested classes do not have access to other members of the enclosing class.
A nested class has access to all the private members of its enclosing class—both fields and methods. Therefore, a public or protected nested class inherited by a subclass has indirect access to all of the private members of the superclass.
Nested class: Use it if your requirements are similar to those of a local class, you want to make the type more widely available, and you don't require access to local variables or method parameters.
A static nested class can inherit: an ordinary class. a static nested class that is declared in an outer class or its ancestors.
No, they are different.
Nested: 'Processor' class outside of Computer can only be accessed as Computer::Processor. Nesting provides context for the inner class (namespace). To a ruby interpreter Computer and Computer::Processor are just two separate classes.
class Computer
class Processor # To create an object for this class, this is the syntax Computer::Processor.new. The Outer class provides context
Child: Below is class inheritance, instance/class methods of Parent class are available to Child. Child/Parent can be instantiated like this Child.new/Parent.new
class Child < Parent
Note that Processor
can only be accessed by Computer::Processor
, just calling Processor
will throw an error. Similarly, calling Child
is good, but calling Parent::Child
will throw a warning (although it will actually run ok).
Some terminology:
Nested
is nested or inner in the sense that it belongs to the namespace introduced by class Parent
. But note as suggested by @Jorg that it is NOT a nested class in the usual sense (cf., in Java).Child
is a subclass or child class of class Parent
, as specified via subclassing, aka inheritance (is-a relationship), Child < Parent
. Roughly, Child
inherits methods from Parent
.To actually understand what happens with nested classes, you need to know how constants work in Ruby.
class
or module
definition.::
can be used to move in the hierarchy of namespaces to select constants. class
definition, e.g. class C; ...; end
, a class is created and is bound to a constant C
which becomes the name of the class.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