If you want to define the same method in multiple classes, and if you define that method in all of each class, you will end up repeating the same description over and over again. (Example 1) Class 1 Class 2 Class 3 Method A Method A Method A Method B Method C Method D When multiple classes have the same method, the more classes you have, the more code you have and the more difficult it is to manage. Let's learn about class inheritance to prevent this.
Defining a class after making a method defined in one class available in another new class is called inheritance.
Class inheritance has a parent-child relationship. The original class is called the parent class, and the newly created class that inherits the methods of the parent class is called the child class. Create a class of "cars", which is a superordinate concept of police cars and trucks, and define common features there. By inheriting the characteristics of the car (parent class), it is not necessary to describe the characteristics of the car in the police car (child class) and truck (child class). As a result, you only have to write the characteristics of the police car and truck, and each characteristic is easy to understand.
When inheriting a class, use "<" when declaring the class and write as follows.
class child class name<Parent class name
end
Now, let's write the example of the car above with the code that actually uses the inheritance of the class. First, define the parent class.
Car class (parent class)
class Car
def speed_up
puts "Accelerate"
end
def speed_down
puts "Decelerate"
end
def horn
puts "Pupoo"
end
end
The parent class defines the common behavior of the car. Next, define each child class. This time, police cars and trucks are defined as Patrol Car and Truck Car, respectively.
PatrolCar class (child class)
class PatrolCar < Car #Class inheritance
def siren
puts "Pea Po Pea Po"
end
end
TruckCar class (child class)
class TruckCar < Car #Class inheritance
def carry
puts "I will carry my luggage"
end
end
By defining a method common to the parent class, the amount of code in the child class is reduced and it is easier to see. Also, this is a big advantage of using inheritance, but you can see from the above code that you can easily reflect the change to the child class by simply changing the common method defined in the parent class.
By using class inheritance, you can write neat code without repeatedly writing common methods, so please write it!
Recommended Posts