Friday, February 12, 2016

Class v. Object: The simplest explanation possible


  • Take a cupcake pan and assume it has only one hole for one cupcake.
  • Prepare a cake mix with vanilla flavor and pour it in the pan.
  • Put the cupcake pan in the oven. And wait until it is cooked.
  • Take it out of the oven and you now have vanilla cupcake.
  • Prepare a cake mix with raspberry flavor this time and put it in the same pan.
  • Put the cupcake pan in the oven. And wait until it is cooked.
  • Take it out and you now have raspberry cupcake.
  • Put each Cupcake on its own plate. You only have two plates.
  • Similarly try bake a lemon cupcake, but wait, you don't have a plate to put it on so you can't bake just yet.
  • Eat the raspberry cupcake.
  • Now bake a lemon cupcake, take it out of the oven and put it on the empty plate where the raspberry cake was.
Illustrated:
The Cupcake pan is the class.
Cupcake();
The vanilla cupcake is the an object made from the class.
Cupcake vanillaCupcake = new Cupcake();
The raspberry cupcake is a second object made from the same class.
Cupcake raspberryCupcake = new Cupcake();
Class is the same, objects are made from a class, objects from the same class can have different attributes.
vanillaCupcake.Flavor = "Vanilla";
raspberryCupcake.Flavor = "Raspberry";
The time the cupcake was in the oven cooking is the object initialization time. How much time it take to create an object, store it in memory and all this shit.
creationTime = Now; //08:01:05 AM 
Cupcake vanillaCupcake = new Cupcake();
initializationTime = Now - creationTime; //08:01:07 AM  
//initializationTime is 2 seconds
The lemon cupcake could be created but no plate for it, this is insufficient memory to create an object.
Cupcake lemonCupcake = new Cupcake(); //ERROR
Eating the raspberry is basically destroying the object and removing it from the memory.
raspberryCupcake = null;
Now that we have an extra plate, we can put our lemon cake in it. We have enough memoery to create another object.
Cupcake lemonCupcake = new Cupcake();
lemonCupcake = "Lemon"
Cupcake are just to explain what class and object are but if you really want to understand it, I do believe OOP is learned in a real life project context. So I started a Youtube channel to teach OOP within a context of a real life project where we build a project from scratch and add functionality episode by episode.
I don't even have ads on this thing, I have a day job and I do this in my free time. I just genuinely want to share my knowledge out there.

My post on reddit
-Hussein

No comments:

Post a Comment

Share your thoughts

Note: Only a member of this blog may post a comment.