The ‘protected’ questions in Java…

Let’s discuss a few questions about using protected in Java in combination with other keywords.

Q1. Can we have methods declared as ‘protected final’ in Java?

Q2. Protected members are not accessible outside the package. How do I write JUnits for them?

Q1. Can we have methods declared as ‘protected final’ in Java?

Short Answer: Yes! 

Explanation

Well yeah.. That’s the short answer. But then an obvious follow-up thing would be, what’s the use?

Now, when most developers think of ‘protected’, their thought process revolves around inheritance and overriding. Mix that with ‘final’, like in this question, and they’d tend to think that these seem contradictory and shouldn’t/ can’t be used together.

But in the current context it helps to think that by using ‘final’, the developer wants to restrict the given implementation only to be used by all users of this class.. Something like.. Duh.. I thought so much about this.. Can’t find a case where this implementation would need to be modified.. And if it did.. Apocalypse! So you’re better off using just this one.

Further, the developer wants to allow only a specific set of classes (the subclasses) to be able to use this member, hence marked it as protected. The java.lang.ClassLoader is a great place to see usage of protected final methods. 

From a design perspective, think of a situation wherein your class provides a template functionality/ pattern and member methods in it define/ implement specific steps of that template. Now you want to allow users to decide where each step/ function can be called within the template, but prevent modification of step’s implementation itself.


Q2. Protected members are not accessible outside the package. How do I write JUnits for them?

Hmm.. this one is quite tricky actually. An obvious answer is that we can create a subclass in test scope and attempt to test based on that. While there’s nothing wrong with that approach, there’s a simpler way. If you’re following the standard guideline of package structure for JUnits, then it’s quite simple. As simple as saying.. The same way we would test a public method, ‘cause a protected method can be accessed directly in corresponding JUnit test class.

This happens because in test scope, the JUnit Test class would be in the same package hierarchy as the source class and hence would be able to access the protected members directly. Food for thought: What would happen if we create a class in src/test package hierarchy with the same name as in src/main and then attempt to test the original one?

For an initial discussion about protected keyword in Java click here.

Rate this post

Leave a Reply