推荐答案
在 Ruby 中,继承是通过 < 符号来实现的。子类通过继承父类,可以获得父类的所有方法和属性。以下是一个简单的示例:
// www.javascriptcn.com code example
class Animal
def speak
puts "Animal speaks"
end
end
class Dog < Animal
def bark
puts "Dog barks"
end
end
dog = Dog.new
dog.speak # 输出: Animal speaks
dog.bark # 输出: Dog barks在这个例子中,Dog 类继承了 Animal 类,因此 Dog 类的实例可以调用 Animal 类中的 speak 方法。
本题详细解读
1. 继承的基本语法
在 Ruby 中,继承的基本语法是使用 < 符号。子类通过 < 符号继承父类,从而获得父类的所有方法和属性。
class ChildClass < ParentClass # 子类的定义 end
2. 方法重写
子类可以重写父类的方法。当子类定义了与父类同名的方法时,子类的方法会覆盖父类的方法。
// www.javascriptcn.com code example
class Animal
def speak
puts "Animal speaks"
end
end
class Dog < Animal
def speak
puts "Dog barks"
end
end
dog = Dog.new
dog.speak # 输出: Dog barks在这个例子中,Dog 类重写了 Animal 类的 speak 方法,因此调用 dog.speak 时会输出 Dog barks。
3. super 关键字
子类可以通过 super 关键字调用父类的同名方法。super 会调用父类中与当前方法同名的方法。
// www.javascriptcn.com code example
class Animal
def speak
puts "Animal speaks"
end
end
class Dog < Animal
def speak
super
puts "Dog barks"
end
end
dog = Dog.new
dog.speak
# 输出:
# Animal speaks
# Dog barks在这个例子中,Dog 类的 speak 方法通过 super 调用了 Animal 类的 speak 方法,然后再输出 Dog barks。
4. 单继承
Ruby 只支持单继承,即一个类只能继承自一个父类。如果需要实现多重继承的效果,可以使用模块(Module)和 include 或 extend 来实现。
// www.javascriptcn.com code example
module Swimmable
def swim
puts "Swimming"
end
end
class Animal
def speak
puts "Animal speaks"
end
end
class Dog < Animal
include Swimmable
end
dog = Dog.new
dog.speak # 输出: Animal speaks
dog.swim # 输出: Swimming在这个例子中,Dog 类通过 include 引入了 Swimmable 模块,从而获得了 swim 方法。