Home » Ruby programming

Ruby | How to initialise base class constructor with the help of derived class object?

Here, we are going to learn how to initialise base class constructor with the help of derived class object in Ruby programming language?
Submitted by Hrithik Chandra Prasad, on August 17, 2019

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.

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 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 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.

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.



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.