Who needs protected variables?

For years, object-oriented programmers knew that one of the main OOP features is encapsulation: an ability to hide and protect object internals. Private and protected properties were invented to support this. But who are we hiding from? From stupid developers who will decide to use our smart framework classes.

In some OOP languages only descendent classes can access protected variables from the ancestor. Java relaxed this rule a little bit and allows accessing protected variables from classes located in the same package. Recently, I had to extend a class from a particular third party framework, which had a protected variable defined. My class was not located in the same package as that third party component… Let’s look at this example.

The code below works fine:

public class Father {

   protected int abc = 25;


public class Son extends Father{

   public Son (){

   System.out.println( "abc= " + abc);



public class MyNewClass {

   public static void main(String[] args) {

     Son son = new Son();

     System.out.println( "Son.abc= "+ son.abc);



The class MyNewClasss is happily printing


Now move the Father and Son to the package com.thirdparty.framework.

After adding the import com.thirdparty.framework.*; to MyNewClass, the code still does not compile complaining that son.abc is not visible. Of course, because designers of the third party framework wanted to protect their precious abc variable, and they wanted to force me to inherit MyNewClass from their Father or Son.. Did they achieve their goal? Not at all. They just forced me to create a Grandson in my default package with a public getter to the abc property.

import com.thirdparty.framework.Son;
public class Grandson extends Son {

   public int getAbc(){
     return abc;


And MyNewClass now looks as follows:

public class MyNewClass {

   public static void main(String[] args) {

     Grandson grandson = new Grandson();

     System.out.println( "Grandson.abc= "+ grandson.getAbc());

It’s just annoying that I need to add the GrandSon because designers of the third party framework decided to make the abc protected.

If you want to restrict the access to a property, make it private and give me a public getter, if needed. If you want to let everyone work with a property, make it public.

But who needs this protected access level?

One thought on “Who needs protected variables?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s