推荐答案
在 Ruby 中,可以通过 super 关键字来调用父类的方法。super 会自动调用与当前方法同名的父类方法,并将当前方法的参数传递给父类方法。
// www.javascriptcn.com code example
class Parent
def greet
puts "Hello from Parent"
end
end
class Child < Parent
def greet
super
puts "Hello from Child"
end
end
child = Child.new
child.greet输出结果为:
Hello from Parent Hello from Child
本题详细解读
1. super 关键字的作用
super 关键字用于在子类中调用父类的同名方法。它会自动查找并调用父类中与当前方法同名的方法,并将当前方法的参数传递给父类方法。
2. super 的两种使用方式
不带参数的
super:如果super不带参数,它会将当前方法的参数自动传递给父类方法。// www.javascriptcn.com code example class Parent def greet(name) puts "Hello, #{name} from Parent" end end class Child < Parent def greet(name) super puts "Hello, #{name} from Child" end end child = Child.new child.greet("Alice")输出结果为:
Hello, Alice from Parent Hello, Alice from Child
带参数的
super:如果super带参数,它会将指定的参数传递给父类方法。// www.javascriptcn.com code example class Parent def greet(name) puts "Hello, #{name} from Parent" end end class Child < Parent def greet(name) super("Bob") puts "Hello, #{name} from Child" end end child = Child.new child.greet("Alice")输出结果为:
Hello, Bob from Parent Hello, Alice from Child
3. super 与 super() 的区别
super:不带括号的super会将当前方法的参数自动传递给父类方法。super():带括号的super不会传递任何参数给父类方法。// www.javascriptcn.com code example class Parent def greet(name) puts "Hello, #{name} from Parent" end end class Child < Parent def greet(name) super() puts "Hello, #{name} from Child" end end child = Child.new child.greet("Alice")输出结果为:
Hello, from Parent Hello, Alice from Child
在这个例子中,
super()没有传递任何参数给父类的greet方法,因此父类方法中的name参数为nil。
4. 使用 super 的场景
扩展父类方法:在子类中重写父类方法时,可以使用
super来调用父类的实现,并在其基础上添加额外的功能。调用父类的构造函数:在子类的
initialize方法中,可以使用super来调用父类的构造函数。// www.javascriptcn.com code example class Parent def initialize(name) @name = name end end class Child < Parent def initialize(name, age) super(name) @age = age end end child = Child.new("Alice", 25)在这个例子中,
super(name)调用了父类的initialize方法,并将name参数传递给它。