13. Overide!


#1

how to print to the console?

class Creature
  def initialize(name)
    @name = name
  end
  
  def fight
    return "Punch to the chops!"
  end
end

# Add your code below!
class Dragon < Creature
  def fight
    return "Breathes fire!"
  end
end


#2

You have to create a so-called Instance of the CLASS-Object
like
me_dragon=Dragon.new("meTheDragon")
then you are able to CALL the fight Method
like
puts me_dragon.fight

===

You might notice that you added the string “meTheDragon” as an argument
this is because at the initialization of the Instance
the Method def initialize(name) is called, this method uses 1 PARAMETER name
If you do not provide an argument
you will run into the error-message

(eval):651: (eval):651:in `initialize': wrong number of arguments (0 for 1) (ArgumentError)
	from (eval):651:in `new'
	from (eval):651

===================================================================
You are learning the inheritance of the Parents Class Methods
With class Dragon < Creature you declare the Dragon-Class to be a child
of the Creature-Class, the Creature-Class being the parent to the Dragon-Class

   Parent
     ^
     |
     |    (inheritance-flow, going up)
     |
   Child

The child will =inherit= the Methods from the parent

==================================================================
But in this exercise
the Dragon-Class fight Methods-name
is shadowing
the Creature-Class fight Methods-name
and if an Instance of the Dragon-Class calls on the fight Method
it will access its own fight Method and NOT that of the Creature-Class

==================================================================
In one of the next exercises you are going to learn to use the super keyword
with which you are able to force the Dragon-Class to use the fight-Method from its Parent
like

# Add your code below!
class Dragon < Creature
  def fight
    puts "Now going to use Parents-fight"
    puts super
    return "Breathes fire!"
  end
end

#3

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