06 April 2011

Java Proficiency - Access control

How can one make a certain method in a certain class only accessible by classes that are defined within the same package as the class of the method? How do you enforce this restriction?
  1. mark the method "public"
    • Right here, you know this one is wrong. Public is accessible by all methods in all packages.
  2. mark the method "package"
    • This isn't even a modifier that exists. So pass. One might be temted by this answer and it is meant to throw you. Know your Java access modifiers.
  3. mark the method "protected"
    • Well this is closer to restriction and in a sense true, however, protected is accessible by the class only and the subclasses of the class.
  4. do not mark the method with a modifier
    • Otherwise known as default. This is the answer we're looking for. Providing no modifier makes the method accessible throughout the same package only.
For reference, see the chart http://download.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html

As with the other technical interview articles, these are meant to be a quick reference for an answer rather than a tutorial on use.

0 comments: