您的位置:首页 > 编程语言 > Ruby

ruby 构造函数_Ruby| 如何在派生类对象的帮助下初始化基类构造函数?

2020-08-03 20:34 1801 查看

ruby 构造函数

During inheritance, if you want to provide values to the base class constructor with the help of derived class object then you are in need to make use of "super" keyword. By implementing super() in the initialize method of the subclass, you can initialize variables of the base class.

在继承期间,如果要在派生类对象的帮助下为基类构造函数提供值,则需要使用“ super”关键字 。 通过在子类的initialize方法中实现super() ,可以初始化基类的变量。

The following are the cases related to super,

以下是与超级相关的情况,

  • super with no arguments:

    超级无参数

    When you only write

    当你只写

    "super" that simply means you are invoking super with no arguments. In such case, Ruby gives a message to the superclass of that object and asks it to invoke the same name method in Base class as the method calling super.

    “ super”仅表示您在不带参数的情况下调用super。 在这种情况下,Ruby将消息传递给该对象的超类,并要求它在基类中调用与调用super的方法相同的名称方法。

  • super with the vacant list:

    超级空缺名单

    The implementation looks like

    实现看起来像

    super(), in this case and no argument is passed to the Parent class of that object even if the base class constructor is having some supplied values in the parameter list.

    super() ,在这种情况下,即使基类构造函数在参数列表中具有一些提供的值,也不会将任何参数传递给该对象的Parent类。

  • super with argument list:

    带有参数列表的超级

    The general implementation looks like

    一般的实现看起来像

    super(val1, val2, ..., valn) in this case. Here all the arguments will be passed to the Superclass which are mentioned in the argument list of super.

    在这种情况下为super(val1,val2,...,valn) 。 在这里,所有参数都将传递给super的参数列表中提到的超类。

Code:

码:

=begin
How to initialize base class variables with derived class object
=end

class Base
def initialize(a,b)
@var1=a
@var2=b
puts "Value of a and b is #{@var1} and #{@var2} in base class"
end
end

class Derived < Base
def initialize(a,b)
super(a,b) #implementation of super
@var3=a
@var4=b
end
def print1
puts "Value of a and b is #{@var3} and #{@var4}"
end
end

ob1=Derived.new(10,20)
ob1.print1
[/code]

Output

输出量

Value of a and b is 10 and 20 in base class
Value of a and b is 10 and 20
[/code]

You can observe in the above code that we are passing arguments in the super() method and those arguments are passed to the Superclass by Ruby resulting in the initialization of Superclass variables.

您可以在上面的代码中观察到我们在super()方法中传递参数,并且这些参数由Ruby传递给超类,从而导致超类变量的初始化。

翻译自: https://www.includehelp.com/ruby/how-to-initialise-base-class-constructor-with-the-help-of-derived-class-object.aspx

ruby 构造函数

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: