Mirror318
Mirror318

Reputation: 12663

Ruby—is nesting classes and child classes the same thing?

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

Upvotes: 6

Views: 1201

Answers (2)

metaphori
metaphori

Reputation: 2811

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.

  • See here for more information.
  • Fundamentally, constants live in a hierarchy of namespaces, where a namespace is a class or module definition.
  • The scope operator :: can be used to move in the hierarchy of namespaces to select constants.
  • In a (first occurrence of a) 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.

Upvotes: 1

ugandharc18
ugandharc18

Reputation: 649

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).

Upvotes: 8

Related Questions