Inheritance and Overrides
Lesson 32 of 48 in Coddy's Ruby for Java Developers course.
Java and Ruby each use one direct class superclass. Java additionally declares implemented interfaces; Ruby includes modules and commonly uses duck typing. Overrides participate in dynamic dispatch in both languages. Ruby does not require a Java-style override annotation, though tests should still verify that the intended method is called.
Java: complete program
import java.util.*;
public class Main {
static class Bird { String sound() { return "chirp"; } }
static class Owl extends Bird { @Override String sound() { return "hoot"; } }
public static void main(String[] args) {
System.out.println(new Bird().sound());
System.out.println(new Owl().sound());
}
}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.soundChallenge
EasyDefine 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)
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Ruby for Java Developers
1Start with Ruby
Run Ruby FilesOutput and CommentsNames and ObjectsInteger ArithmeticTruth and Boolean LogicString OperationsSymbols and KeysRecap: Packing Slip2Flow and Methods
Conditional ValuesCase and RangesLoops and Early ExitMethods and ReturnsDefaults and KeywordsRecap: Sensor Run5Objects and State
Modules as NamespacesClasses and InstancesReaders and WritersValidated ConstructionRecap: Wallet8Lending Desk Project
Lending Desk: CatalogLending Desk: Borrow3Collections and Blocks
Arrays and IndexingHashes and Missing KeysYielding to a BlockMap and SelectReduce and PredicatesRecap: Repeated Codes6Composition and Dispatch
Composing ObjectsInheritance and OverridesExtending with SuperModules as MixinsDuck-Typed CollaboratorsRecap: ReceiptsPractice on your own: Online Ruby compiler