×

Ruby Tutorial

Ruby Basics

Ruby Control Statements

Ruby Methods

Ruby Classes and Methods

Ruby Arrays

Ruby Sets

Ruby Strings

Ruby Classes & Objects

Ruby Hash

Ruby Tools

Ruby Functions

Ruby Built-in Functions

Misc.

Ruby Programs

Ruby Initializing Base Class Constructor with Derived Class Object

By IncludeHelp Last updated : December 01, 2024

Initializing Base Class Constructor with Derived Class Object

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.

Understanding the Use of 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 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.

Example for Initializing Base Class Constructor with Derived Class Object

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