ByteBrawl - Protected - Access Modifiers - Encapsulation

Access Modifiers - Protected

The protected access modifier allows access to the class, method, or variable from the same package and also from subclasses (even if they are in different packages). It is more permissive than default but more restrictive than public.

You might not know what a subclass is right now, but don't worry, the next section is all about Inheritance, which includes subclasses. For now, just know that a subclass is a class that inherits fields and methods from another class, in addition to adding its own fields, methods, and functionality. It would be like copy and pasting a class, renaming it, and then adding new members/functionality to it. Here's an example of the protected keyword in action:

ProtectedExample.java

Main.java

If you try running the above, you'll notice that there is a compilation error because Main.java both isn't in the same package as ProtectedExample.java (the default package is not the same as the example package) and also isn't a subclass of ProtectedExample. However, if we move Main.java into the example package, it will work:

In the above example, we didn't do anything with subclasses. However, we could still access myProtectedNum because Main.java was put in the same package as ProtectedExample.java.