OOP and Access Control Tutorial I :Private vs Public (and Why)

Starting from this post, I will go over some important concept in OOP. The first lesson is Access Control: the _ private _ and _ public _ keywords. You see those words in different forms in many OOP languages. 

Below is an example of Java code,

public class Foo{
  private string privateMethod(){System.out.printlln("private method called");}
  public string pubicMethod(){System.out.printlln("public method called");}

Because this is the first post, I will show you why it is important to use access control properly in OOP before dive into the what and how’s. We will go over this with a simple example.

Suppose you are writing a program for a microwave oven. You take out you note book and start to plan.

What does a microwave do?

  • Shoot microwaves to agitate water modules
  • Let its users to set a time 
  • Let its users to stop its operation
  • Turn on its internal light 
  • Turn off its internal light

Function prototypes

  • shootMicrowave()
  • start(time)
  • stop()
  • turnonLight()
  • turnoffLight()

Function Implementations (you defaulted everything to public for convenience)

public void shootMicrowave()
     //you asked Percy Spender to fill in this very complicated function body for you

public void start(int time)
     while (time>0)

public void stop()
    //again, you asked Percy to stop the microwaves for you

public void turnonLight()
  //connect your circuit

public void turnoffLight()
  //disconnect your circuit

You layed on your back and think your job is done. But now Percy comes over and tell you that anything you declared public, would be represented as a button on the magic box that users can click. 

Now you need to rethink about your keywords. 

  • shootMicrowave():

Do you really want your kids shoot microwaves around? It would be a nice idea if you decided to become a underground firearm smuggler and spend your life in jail.

So now we have, private shootMicrowave()

  • start(time):

Look at your microwave and we know we should key this public start(time)

  • stop():

User should be able to stop the microwave so food don’t get overcooked. We keep it as public stop()

  • turnonLight()/turnoffLight():

It would be a nice feature if we can use the microwave as a lamp! But Percy comes over and comments that we should restrict the purpose of the magic box to just heat up food. And you agreed. 

Now we have private turnonLight and private turnoffLight() 

Your microwave oven is ready to ship! If you have any questions please leave a comment below.

« The Birth of This Super Awesome Website: Depolying Rails App To Heroku + Custom Domain Names Simple Ruby On Rails Mass Assignment Testing Part I : Through Browser Concole »