20/20 - Up, Up, and Away! - I'm confused!


#1
class Message
  @@messages_sent = 0
  
  def initialize(from, to)
    @@messages_sent += 1
    @from = from
    @to = to
  end
end

class Email < Message
  def initialize(from, to)
    super
  end
end

This is my answer, which works. The issue is that I’m confused. If Email inherits from Message and we want our initialize to be exactly the same, what’s the point of even defining it again and using super in it? Seems like writing code for nothing or am I missing something?


#2

The separate classes permit special methods in the derived class that are not in the super class. The above is just a skeleton so doesn’t really demonstrate that.

It does demonstrate that only one initialize method is needed between the two, and both classes increment the @@messages_sent variable.

class Message
  @@messages_sent = 0
  def initialize(from, to)
    @from = from
    @to = to
    @@messages_sent += 1
  end
  def self.messages_sent
    @@messages_sent
  end
end

class Email < Message
  def initialize(from, t0)
    super
  end
end

my_message = Message.new('me', 'you')

my_email = Email.new('me', 'you')

p Message.messages_sent    # =>  2

p Email.messages_sent      # =>  2

#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.