Showing posts with label class. Show all posts
Showing posts with label class. Show all posts

Monday, February 7, 2011

Subclasses and Superclasses in Ruby

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?