No. | title |
---|---|
1 | Markdown memorandum |
2 | Current article |
3 | Second post |
How to write class inheritance
class Apple < Fruit
#Child class#Parent class
end
In the above case, Fruit is the parent class and Apple is the child class.
class Fruit
def initialize(fruit_name, fruit_color)#(First argument,Second argument)Formal argument
#The initialize method is processed at the same time as the new method is executed when the instance is created. No new description is needed for the call.
@fruit_name = fruit_name
#@fruit_name is what is called an instance variable.
@fruit_color = fruit_color
end
def name
puts "this is#{@fruit_name}is."#{value}でvalueの展開を行なっています。
end
# def color
# puts "#{@fruit_color}The color."
# end
end
class Apple < Fruit
#Child class#Parent class
def name
puts "This is delicious#{@fruit_name}is."
#It can handle instance methods and instance variables defined in the parent class. It is a feature of class inheritance.
#It is also possible to overwrite the instance method by using the one with the same name as the instance method of the parent class in the child class.
end
def color
puts "beautiful#{@fruit_color}The color."
#You can also handle instance methods that are only child classes.
end
end
apple = Apple.new("Apple", "Red")#The actual argument, the actual argument and the formal argument must match the number.
apple.name #Generated instance name.You are calling an instance method with an instance method name.
apple.color
The output is ** This is a delicious apple. **** It is a beautiful red color. ** ** It will be.
Recommended Posts