【问题标题】:Ruby—is nesting classes and child classes the same thing?Ruby——嵌套类和子类是一回事吗?
【发布时间】:2023-03-13 15:26:01
【问题描述】:

在下面的例子中NestedChild 有什么区别?只是同一事物的语法不同吗?

class Parent
  class Nested
    ...
  end
end

class Child < Parent
  ...
end

【问题讨论】:

    标签: ruby inheritance


    【解决方案1】:

    ,它们是不同的。

    嵌套:Computer 外部的“处理器”类只能作为 Computer::Processor 访问。嵌套为内部类(命名空间)提供上下文。对于 ruby​​ 解释器而言,Computer 和 Computer::Processor 只是两个独立的类。

     class Computer
      class Processor # To create an object for this class, this is the syntax Computer::Processor.new. The Outer class provides context
    

    Child:下面是类继承,Parent类的实例/类方法可供Child使用。 Child/Parent 可以像这样 Child.new/Parent.new 实例化

    class Child < Parent
    

    注意Processor只能Computer::Processor访问,调用Processor会抛出错误。同样,调用Child 很好,但调用Parent::Child 会抛出警告(虽然它实际上会运行正常)。

    【讨论】:

    • 请注意,嵌套在模块 M 中的类 C 的引用方式完全相同:M::C
    【解决方案2】:

    一些术语:

    • Nestednestedinner,因为它属于 Parent 类引入的 namespace。但请注意,正如@Jorg 所建议的,它不是通常意义上的嵌套类(参见in Java)。
    • ChildParent 类的 子类子类,通过 subclassing 指定,也称为 inheritance (是关系),Child &lt; Parent。大致上,Child 继承自 Parent 的方法。

    要真正了解嵌套类会发生什么,您需要了解常量在 Ruby 中的工作原理。

    • 请参阅here 了解更多信息。
    • 从根本上说,常量存在于命名空间的层次结构中,其中命名空间是 classmodule 定义。
    • 范围运算符:: 可用于在命名空间层次结构中移动以选择常量。
    • 在(a 的第一次出现)class 定义中,例如class C; ...; end,创建了一个类并绑定到常量C,该常量成为类的名称。

    【讨论】:

    • 我认为值得一提的是,与子类不同,嵌套类不会为您提供任何共享功能。我花了一段时间才明白
    • 理解事物的问题是人们期望孤立地或相似地理解它们。使用嵌套时可以想象共享哪些功能以及为什么(如果您可以追溯您最初的疑问)?
    • @maxpleaner:实际上,他们。这几乎就是嵌套类的定义,这也是 Ruby 没有嵌套类的原因。
    • "Nested 是类Parent嵌套内部 类。" ——不,不是。 Ruby 没有嵌套类。 constant Nested 在由常量 Parent 引用的类内部命名空间。但是这两个之间绝对没有任何关系。
    • "nested/inner" 这里指的是常量的范围。但我同意这可能会产生误导。最好更新帖子。
    猜你喜欢
    • 2015-07-18
    • 1970-01-01
    • 1970-01-01
    • 2018-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多