As discussed in the previous chapter, inheritance is one of the fundamental concepts in object-oriented programming. Along with subtyping polymorphism, it gives us the is/a relationship. A Car
object can be handled as a Vehicle
object. A Truck
object can be handled as a Vehicle
object too. On one hand, this kind of abstraction makes our code thinner, because the same piece of code can handle operations for both Car
and Truck
objects. On the other hand, it gives us the option to extend our code to new types of Vehicle
objects by simply adding new classes such as Bike
and Van
without modifying it.
When we deal with such scenarios, one of the trickiest parts is the creation of objects. In object-oriented programming, each object is instantiated using the constructor of the specific class, as shown in the following code:
Vehicle vehicle = new Car();
This piece of code implies a dependency between the class which instantiates an object and the class of the instantiated object...