How Polymorphism Works and Using Super in Ruby
In this lesson, we are going to talk about another important concept in object-oriented programming called polymorphism. Polymorphism occurs when a class that inherits from a parent class changes the behavior of a method in the parent class.
Guide Tasks
  • Read Tutorial
  • Watch Guide Video
Video locked
This video is viewable to users with a Bottega Bootcamp license

In this guide we are going to discuss another important concept in object-oriented programming called polymorphism. Polymorphism occurs when a class that inherits from a parent class overrides the behavior provided by the parent class.

To see a basic example we're going to continue working with our API Connector class.

class ApiConnector
  def initialize(title:, description:, url: 'google.com')
    @title = title
    @description = description
    @url = url
  end

  def api_logger
    puts "API Connector starting..."
  end
end

I've added a new method to our class called api_logger.

Next I'll create a class called PhoneConnector inherits from our ApiConnector. After we instantiate the class it can call the api_logger method that we created in the parent class.

class PhoneConnector < ApiConnector
end

phone = PhoneConnector.new(title: 'My Title', description: 'Some content')
phone.api_logger

If you run this code in the terminal, you will get the message API Connector Starting...

So How Does Polymorphism Fit In?

Polymorphism occurs when the PhoneConnector class overrides the behavior of api_logger method, like in the code below:

class PhoneConnector < ApiConnector
  def api_logger
    puts "Phone call API connection starting..."
  end
end

phone = PhoneConnector.new(title: 'My Title', description: 'Some content')
phone.api_logger

Now, if you run the same code, it prints Phone call API connection starting...

This type of polymorphism implementation is quite common in Ruby development and helps developers give some custom behavior to an application.

Next, what happens when we want to combine the behavior from the ApiConnector and PhoneConnector api_logger methods?

To do that, simply insert the word super in the api_logger method of the PhoneConnector class.

class PhoneConnector < ApiConnector
  def api_logger
    super
    puts "Phone call API connection starting..."
  end
end

If you run this code, both the messages get displayed.

API Connector starting...
Phone call API connection starting...

So what's making this possible? When Ruby saw the method super it went to the parent class and looked for a method with an identical method and ran that method. Then, it came back to the method in the child class and finished running the rest of the code in the method.

So, that's how polymorphism and super work in Ruby.