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

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

Output

输出量

Value of a and b is 10 and 20 in base class
Value of a and b is 10 and 20

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 构造函数

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值