OOP (object oriented programming) inheritance. You can think of inheritance as a ‘is a’ relationship. A car is a automobile. A lion is a cat. A man is a human. These are all relationships that can be defined by using inheritance. The child class has all the features of the parent.
In code it would look like this:
class Automobile
end
class Car < Automobile
end
Ok but what if we want to use functionality from another class that doesn’t exactly fit into that ‘is a’ relationship? Well it probably fits into a different type of relationship know as a ‘has a’ relationship, which uses a concept know as composition. Composition is just using another class within a class. Lets say that we have a class that defines different ways automobiles can move. Well a movement is not a car so inheritance won’t work. But a car has a movement so we can use composition! Lets see what this looks like in code:
class Movement
def drive
puts "We are driving"
end
end
class Automobile
end
class Car < Automobile
def initialize
@movement = Movement.new
end
def drive
@movement.drive
end
end
Composition example from previous challenge
class AussieDate
def initialize(year, month, day, hour = 0, min = 0)
@date = DateTime.new(year, month, day, hour, min)
end
# methods omitted
end
- morning challenge and sample solution below (product_list_test.rb and product_list.rb)
- challenge auction_list_test.rb below
- Implement a class that uses AussieDate
- Implement a class that uses the Auction Item List class
Implement the exercises in:
Inheritance Versus Composition