Hackety Hacking Problem Inheritance in classes

From OLPC
Jump to navigation Jump to search
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.

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)