Wednesday, January 1, 2014

Who needs protected variables?

At 11:42 AM on Aug 25, 2006, Yakov Fain DeveloperZone Top 100 wrote:

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 MyNewClasss is happily printing 
abc=25 
Son.abc=25 

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()); 



Its just annoying that I need to add the GrandSon just because designers of this 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?

No comments: