So last night I began learning about Classes and inheritance. A class can only inherit from one other class. Makes sense, but the thing I was wondering about all day is this:
Say you have a parent class with a child class, that child class (child1) has a child class of its own.(child2) I am sure this kind of thing is a regular occurrence. So does child2 also inherit from the parent class in addition to inheriting from child1? My guess was yes, it does. So I came home and whipped up some code to test this theory.
class Pet
def method1
puts "I am a good pet."
end
end
class Cat < Pet
def method2
puts "I am a cat. Meow!"
end
end
class Oskar < Cat
def method3
puts "I am the BEST cat of all time."
end
end
oskar = Oskar.new
puts "Oskar says:"
oskar.method1
oskar.method2
oskar.method3
Success! Oskar is a child of the Cat class, which is a child of the Pet class, and Oskar inherits all the logic from the previous generations. Just as I suspected. So a class can only inherit directly from one class, as in Oskar < Cat, but it inherits directly from all classes that come before its parent in the great circle of life.
Is there a bit of code to list all the inherited logic for a particular class? Also, what do you call more than one child class? Childs? Children? Chirren?
Subclass is usually what you call child classes. And superclass is the parent class.
ReplyDeleteOskar.superclass #=> Cat
Cat.superclass # => Pet
You can also see the entire superclass hierarchy by calling ancestors.
Oskar.ancestors # => [Oskar, Cat, Pet]
Ruby doesn't give you an easy way to from superclass to subclasses, but it's not too hard and Rails' ActiveSupport libarry makes it ridiculously easy.
require 'active_support'
Cat.subclasses # => [Oskar]
You might try naming all your method's something like details, and then you can make each method call it's superclass method's detail method, like so:
class Pet
def details
puts "I am a good pet."
end
end
class Cat < Pet
def details
super
puts "I am a cat. Meow!"
end
end
class Oskar < Cat
def details
super
puts "I am the BEST cat of all time."
end
end
This is when subclassing gets really interesting.