Subclasses
Part of the Object Oriented Programming section of Coddy's Ruby journey. Lesson 22 of 57.
Inheritance builds a new class on an existing one. class Dog < Animal makes Dog a subclass of Animal, its superclass. A dog has every method of an animal, including initialize, plus the methods Dog adds:
class Animal
attr_reader :name
def initialize(name)
@name = name
end
def eat
"#{name} is eating"
end
end
class Dog < Animal
def fetch
"#{name} fetches the ball"
end
end
rex = Dog.new("Rex")
puts rex.eat
puts rex.fetchOutput:
Rex is eating
Rex fetches the ballThe added methods belong to the subclass only. A plain Animal does not have them, and a sibling class such as Cat does not see the methods of Dog:
class Animal
def breathe
"breathing"
end
end
class Dog < Animal
def fetch
"fetching"
end
end
class Cat < Animal
end
puts Cat.new.breathe
begin
Cat.new.fetch
rescue NoMethodError => e
puts e.message
endOutput:
breathing
undefined method `fetch' for an instance of Catsuperclass names a class's parent. A Ruby class has exactly one superclass, and a class declared without < inherits from Object, which gives every object methods such as to_s and inspect:
class Animal
end
class Dog < Animal
end
puts Dog.superclass
puts Animal.superclass
puts Object.superclassOutput:
Animal
Object
BasicObjectInheritance fits an is-a relation: a dog is an animal, a savings account is an account. Shared behaviour goes into the superclass once, and each subclass adds what makes it different. In this section each class lives in its own file, and the superclass's file is loaded first:
# main.rb
require_relative 'animal' # the superclass first
require_relative 'dog' # class Dog < Animal needs Animal
require_relative 'cat'Challenge
EasyComplete the classes. Vehicle stores a name and a number of wheels and has describe, which returns Mini has 4 wheels. Car and Bike are subclasses of Vehicle that do not define initialize. Car adds honk, returning Mini says beep, and Bike adds ring, returning BMX rings.
The supplied code reads lines car Mini or bike BMX, creates a Car with 4 wheels or a Bike with 2, and prints describe, the sound (honk or ring) and the superclass of the object's class.
Your code goes in vehicle.rb, car.rb and bike.rb. main.rb holds the supplied input/output code and cannot be edited.
Try it yourself
require_relative 'vehicle'
require_relative 'car'
require_relative 'bike'
# Supplied input/output code: keep it as it is
input = []
while (line = gets)
input << line.chomp
end
input.each do |line|
kind, name = line.split(" ", 2)
if kind == "car"
v = Car.new(name, 4)
sound = v.honk
else
v = Bike.new(name, 2)
sound = v.ring
end
puts v.describe
puts sound
puts v.class.superclass
end
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Classes and Objects
Working With FilesDefining ClassesInstance VariablesMethods and selfto_s and inspectRecap - Library Card7Polymorphism and Duck Typing
PolymorphismDuck TypingAbstract Methodscase and ClassesRecap - Payment Methods2Accessors and Self
Readers and WritersCustom Settersself in MethodsIdentity and EqualityRecap - Contact List8Special Methods
Equality and hashOperator MethodsIndexing and AppendingCustom CollectionsRecap - Fractions11Project: Library Management
Books and MembersBorrowing Books3Class Methods and Variables
Class MethodsClass Instance VariablesConstantsFactory MethodsRecap - Coupon CodesPractice on your own: Online Ruby compiler