Menu
CoddyTech

Inheritance and Overrides

Lesson 32 of 48 in Coddy's Ruby for C# Developers course.

C# classes and Ruby classes have one direct class superclass, with interfaces or modules providing additional forms of reuse. C# overriding requires the appropriate virtual/override declarations; Ruby ordinary method lookup is dynamic without those modifiers. Hiding a C# member is a different operation from overriding it. Verify the actual invoked behavior after porting.

C#: complete program

using System;
using System.Collections.Generic;
using System.Linq;
Bird bird=new Bird();Bird owl=new Owl();Console.WriteLine(bird.Sound());Console.WriteLine(owl.Sound());
class Bird {public virtual string Sound()=>"chirp";}
class Owl:Bird {public override string Sound()=>"hoot";}

Ruby: complete program

class Bird
  def sound; "chirp"; end
end
class Owl < Bird
  def sound; "hoot"; end
end
puts Bird.new.sound
puts Owl.new.sound
challenge icon

Challenge

Easy

Define Fee#cost(units) returning units*2. DiscountFee inherits Fee and overrides cost, returning units (all units nonnegative). solve reads base or discount followed by units; construct the chosen type.

Return text from solve(input) without printing. The locked driver prints the returned text with one final newline and checks required public APIs independently.

Your code goes in exercise.rb, fee.rb, discount_fee.rb. main.rb holds the supplied input/output code and cannot be edited.

Try it yourself

require_relative 'exercise'
require_relative 'fee'
require_relative 'discount_fee'
def check(value)
  raise 'Public API check failed' unless value
end
check(DiscountFee.new.is_a?(Fee))
check(Fee.new.cost(7) == 14 && DiscountFee.new.cost(7) == 7)

puts solve(STDIN.read)
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Ruby for C# Developers

Practice on your own: Online Ruby compiler