OOP and Access Control Tutorial II: Protected

Your microwave is working smoothly now. It’s 2am at in the morning and you are writing a program to make a quantum microwave.

Suddenly you get very very hungry. You put your last piece of frozen pizza in the microwave. You pressed that shiny ( public ) start button but nothing happened.You pressed again and still nothing happened…Panicked, you called Percy . He came and told you that the microwave is broken and the only way to fix it is to open the back cover of the microwave. However, during your initial development, you did this:

private void openBackDoor();

It means no one can open it unless the microwave decides to open itself. 

What do you do now? You do not want to make it public because you do not want anything to just open the back cover, but you also do not want to make it private because in desperate situations like this, you need someone to open it.

Now you recall in java, you see this often,

class Bar 
 protected void foo(){}; 

The protected modifier! In Java, _ protected _ means 

  • Self accessibility
  • Same package accessibility
  • Inheritance accessibility

If you are not familiar with inheritance or java packages, don’t worry. Just keep in mind that protected is between private and _ public _: it allows classes with certain privilege to access it. In this case, you changed,

private void openBackDoor();


protected void openBackDoor();

And since Percy invented the microwave, he is considered a parent of the microwave class, and gained access to the method.

He proceeded to fix your microwave and you finally heated up that long-waited, much-wanted piece of pizza. 

« Simple Ruby On Rails Mass Assignment Testing Part II : Through Post Request Change Terminal's Title On Mac »