Hello!
Today we will be learning about a topic in not only Objective-C, but in object oriented programming called polymorphism which basically just means "many forms." Today's post will be a bit shorter than usual, so let's dive right in.
First, download the starter project here.
Today we will be learning about a topic in not only Objective-C, but in object oriented programming called polymorphism which basically just means "many forms." Today's post will be a bit shorter than usual, so let's dive right in.
First, download the starter project here.
Polymorphism
Polymorphism has close ties to inheritance. In the starter project there are three custom classes called Vehicle, Motorcycle, and Bicycle. Vehicle is the superclass of them all. Motorcycle subclasses Vehicle. Bicycle subclasses Motorcycle. First look inside the Vehicle.m file.
Now look at the Motorcycle.m file.
Now look at the Bicycle.m file.
What! There is nothing there! Well let's go through each file step by step using our previous knowledge of inheritance. First in Vehicle.m we declare a method called printNumberOfWheels. Then since Motorcycle is a subclass of Vehicle, it will inherit the method of printNumberOfWheels. But in Motorcycle.m we override that method, making it print out a different statement. Finally, since Bicycle subclasses Motorcycle, it also inherits the method of printNumberOfWheels. Now run the project.
There is the output. Let's look at where we create and initialize the objects in ViewController.m.
First Vehicle's printNumberOfWheels method is called. So it make sense that "Vehicles have 4 wheels" is outputted first. Then Motorcycle's is called. So then "Motorcycles and bicycles have 2 wheels" is outputted. Then Bicycle's is called which also makes sense because since we did not override the method in Bicycle.m, it has the same functionality as Motorcycle.m's so it will also output "Motorcycles and bicycles have 2 wheels."
Well, that was pretty easy! Finally a post without memorizing syntax! As always, feel free to leave a suggestion, comment, or question below, or email me at [email protected]. Next we will be learning about dynamic binding and dynamic typing.
Thank you!
Zachary Cmiel
The PoKoBros
Well, that was pretty easy! Finally a post without memorizing syntax! As always, feel free to leave a suggestion, comment, or question below, or email me at [email protected]. Next we will be learning about dynamic binding and dynamic typing.
Thank you!
Zachary Cmiel
The PoKoBros