【发布时间】:2023-03-13 15:26:01
【问题描述】:
在下面的例子中Nested 和Child 有什么区别?只是同一事物的语法不同吗?
class Parent
class Nested
...
end
end
class Child < Parent
...
end
【问题讨论】:
标签: ruby inheritance
在下面的例子中Nested 和Child 有什么区别?只是同一事物的语法不同吗?
class Parent
class Nested
...
end
end
class Child < Parent
...
end
【问题讨论】:
标签: ruby inheritance
不,它们是不同的。
嵌套: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。
一些术语:
Nested 是 nested 或 inner,因为它属于 Parent 类引入的 namespace。但请注意,正如@Jorg 所建议的,它不是通常意义上的嵌套类(参见in Java)。Child 是 Parent 类的 子类 或 子类,通过 subclassing 指定,也称为 inheritance (是关系),Child < Parent。大致上,Child 继承自 Parent 的方法。要真正了解嵌套类会发生什么,您需要了解常量在 Ruby 中的工作原理。
class 或 module 定义。:: 可用于在命名空间层次结构中移动以选择常量。 class 定义中,例如class C; ...; end,创建了一个类并绑定到常量C,该常量成为类的名称。【讨论】:
Nested 是类Parent 的嵌套 或内部 类。" ——不,不是。 Ruby 没有嵌套类。 constant Nested 在由常量 Parent 引用的类内部命名空间。但是这两个类之间绝对没有任何关系。