3

From the developer guides we have the following definition:

This means that the method or variable is visible to any inner classes in the defining Apex class, and to the classes that extend the defining Apex class. You can only use this access modifier for instance methods and member variables. Note that it is strictly more permissive than the default (private) setting, just like Java.

However, I am still unsure when to use this and how it differs from the public modifier.

1 Answer 1

10

The protected access modifier is much more like private than public. In fact, for a class which is not virtual nor abstract, this access modifier would be the same as private (though it's not allowed). However, once you allow extension of the class, you can then see it in overriding implementations.

public class Class1
{
    protected void foo()
    {
        // this access would just be the same as private
        // however, the class will not compile
    }
}
public virtual class Class2
{
    protected void foo()
    {
        // now this class will compile
        // this method can only be seen by extensions of this class
    }
}
public class Class3 extends Class2
{
    public static bar()
    {
        // cannot see the foo method here because the method is static
        // the below line will cause compile fail
        new Class1().foo();
    }
}
public class Class4 extends Class2
{
    public void baz()
    {
        // now that you are within an instance which extends the definition,
        // you are able to see the method
        this.foo();
    }
}
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .