Robotics C++ Physics II AP Physics B Electronics Java Astronomy Other Courses Summer Session  

Access Specifiers


public

public classes, methods, and variables can be accessed from everywhere.

 

private

private methods and variables can only be accessed within the same class to which the methods and variables belong. private methods and variables are not visible within subclasses and are not inherited by subclasses. So, the private access specifier is opposite to the public access specifier.

 

default (no specifier)

If you do not set access to specific level, then such a class, method, or variable will be accessible from inside the same package (or project) to which the class, method, or field belongs, but not from outside this project. This access-level is convenient if you are creating packages. For example, a geometry package that contains Square and Tiling classes, may be easier and cleaner to implement if the coordinates of the upper-left corner of a Square are directly available to the Tiling class but not outside the geometry package. NOTE: Inheritance is not required here.

 

protected

protected methods and variables can only be accessed within the same class to which the methods and variables belong, within its subclasses, and within classes of the same package or project, but not from anywhere else. You use the protected access level when it is appropriate for a class's subclasses to have access to the method or field, but not for unrelated classes. NOTE: Inheritance is involved here.

 

Say What? protected versus default - cut to the solution     

Protected access modifier is a little tricky and you can say that it is a superset of the default access modifier.

Protected members are the same as the default members as far as the access in the same package or project is concerned.

The difference is that the protected members are also accessible to the subclasses of the class in which the member is declared which are outside the package or project in which the parent class is present.

 

Conclusion and solution to this issue: We will not use default access specifiers - clearly state whether the access is public, private or protected in all code. For the AP exam, default is not used.