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:
- 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.
- 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).
- 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.
- 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:
1 2 3 4 5 6 7 8 |
package com.coddicted.packageA; public class Parent { protected void greet() { System.out.println("Hello from Parent!"); } } |
1 2 3 4 5 6 7 8 |
package com.coddicted.packageA; public class ParentUser { public static void main(String[] args) { new Parent().greet(); // prints: Hello from Parent! } } |
Output of running the main method in ParentUser class is:
Hello from Parent!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
package com.coddicted.packageB; import com.coddicted.packageA.Parent; public class Child extends Parent { public String otherChildMethod() { greet(); // Calls the method in Parent class } public static void main(String[] args) { Child c = new Child(); c.greet(); //prints: Hello from Parent! c.otherChildMethod(); // prints: Hello from Parent! } } |
Output of running the above main method in Child class is:
Hello from Parent!
Hello from Parent!
1 2 3 4 5 6 7 8 9 |
package com.coddicted.packageB; public class ChildUser { public static void main(String[] args) { Child child = new Child(); System.out.println(child.otherChildMethod()); // child.greet(); // not allowed } } |
Output of running above main method in ChildUser class:
Hello from Parent!
For some interesting questions about using protected in Java, Read This!