Protected Visibility

Download java eBook

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.

Stats

Contributors: 1
2016-02-18
Licensed under: CC-BY-SA

Not affiliated with Stack Overflow
Rip Tutorial: info@zzzprojects.com

Download eBook