Protected access modifier in Java

As per the official java documentation from Oracle:

“The protected modifier specifies that the member can only be accessed within its own package (as with package-private) and, in addition, by a subclass of its class in another package.”

What this means is:

  1. Say, a concrete class Parent in package com.coddicted has a protected method named protectedMethod. Then any other class in the same package com.coddicted would be able to instantiate the Parent class and call the protectedMethod directly on that instance.
  2. A subclass of Parent named Child would be able to call the protectedMethod within it irrespective of which package the Child class is in. It can, of course, override the parentMethod assuming it’s not declared final (confused? See this).
  3. An object of class Child created within the class itself, would be able to call the protectedMethod directly. However, the same is not allowed if the object of Child is created in some other class.
  4. A protected static method in Parent is also accessible in Child class.

Ok, enough of theory! We know you programmers like to see the code more than anything. So let’s jump right into it.

Here’s the visual representation of our project structure:

Below is the code for above 4 classes:

Output of running the main method in ParentUser class is:

Hello from Parent!

Output of running the above main method in Child class is:
Hello from Parent!
Hello from Parent!

Output of running above main method in ChildUser class:

Hello from Parent!

For some interesting questions about using protected in Java, Read This!

Rate this post

Leave a Reply