Java Language Visibility (controlling access to members of a class) Protected Visibility

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

Protected visibility causes means that this member is visible to its package, along with any of its subclasses.

As an example:

package com.stackexchange.docs;
public class MyClass{
    protected int variable; //This is the variable that we are trying to access
    public MyClass(){
        variable = 2;
    };
}

Now we'll extend this class and try to access one of its protected members.

package some.other.pack;
import com.stackexchange.docs.MyClass;
public class SubClass extends MyClass{
    public SubClass(){
        super();
        System.out.println(super.variable);
    }
}

You would be also able to access a protected member without extending it if you are accessing it from the same package.

Note that this modifier only works on members of a class, not on the class itself.



Got any Java Language Question?