John Maclean wrote:
> Thanks for another fast response. Inheritance - I'm going to get this
> -tonight-!
> 
> recap;
> # the parent class
> cat fx/ruby/chap3/class_Song.rb
> #!/usr/bin/env ruby
> class Song
>   def initialize(name, artist, duration)
>     # define instance variables
>     @name = name
>     @artist = artist
>     @duration = duration
>   end
> 
>   def to_s
>     # method for displaying these instancess
>   "Song: #@name--#@artist (#@duration)"
>   end
> end
> 
> # the child class
> 
> jayeola@tp20$ cat fx/ruby/chap3/class_KaraokeSong.rb
> #!/usr/bin/env ruby
> require 'class_Song.rb'
> 
> # test if this class has been loaded correctly
> Object.const_defined?(:Song)
> 
> class KaraokeSong < Song
>   def initialize(name, artist, duration, lyrics)
>     super(name, artist, duration)
>     @lyrics = lyrics
>   end
> 
>   def to_s
>     super + " [#@lyrics]"
>   end
> end
> 
> #song = KaraokeSong.new("My Way", "Sinatra", 225, "And now, the...")
> #song = KaraokeSong.new("Sinatra", 225, "And now, the...")
> #song.to_s
> #song.inspect
> 
> 
> How do we get KaraokeSong to acquire it's parent's attributes -without-
> hadrcoding "def initialize(name, artist, duration, lyrics)", unless one
> has to? From the book I get the impression that you can get away with
> specifying the child's stuff and that it will take properties from it's
> parent with the keyword super....

If the child needs additional parameters (or otherwise overrides
the corresponding method in the parent class), you must* define
the method in the child (super will run the parent's method like
in your #initialize above). When the parent's behaviour is adequate,
you do not need to define a method, it is automatically inherited.

An alternative would be to just have an accessor for @lyrics; that
way you would not need to define #initialize, but you would need to
call #lyrics= to set the lyrics initially., which on the surface
would seem the more cumbersome way.


E

* Not strictly true; you could circumvent this with some careful
  metaprogramming but it really is not worth it in this situation.

-- 
Posted via http://www.ruby-forum.com/.