Hackety Hacking Problem Inheritance in classes

From OLPC
Revision as of 22:02, 24 October 2007 by Anubhavit (talk | contribs) (New page: == Problem Statement == To be done.... == Sample Output == <pre> To be done....</pre> == Curriculum Connections == To be done.... == Solution == <pre> # class Song def to_s ...)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Problem Statement

To be done....

Sample Output

To be done....


Curriculum Connections

To be done....

Solution

# 
class Song
  def to_s
       "#{@name}--#{@artist} (#{@duration})"
  end
  
  def initialize(name, artist, duration)         #When you call Song.new to create a new Song object, Ruby creates an                                    
  uninitialized object and then calls that object's initialize method, passing in any parameters that were passed to new. This gives you a chance to write code that sets up your object's state.

   @name = name
   @artist = artist 
   @duration = duration
  end

end

# method new used to create object

aSong = Song.new("Eye of Tiger", "Survivor", 260)
puts("To Show the data present in Super(Parent)Class")
puts(aSong.to_s)

class KaraokeSong < Song # Inheriting class KaraokeSong from Song
   def to_s
     super + " [#{@lyrics}]"
   end

   def initialize(name, artist, duration, lyrics)
     super(name, artist, duration)
     @lyrics = lyrics
   end
end
print("\n") # To leave a blank line

aSong = KaraokeSong.new("Eye of Tiger", "Survivor", 260, "Rising up....")
puts("To Show the data present in Sub(Child) Class")
puts(aSong.to_s)