Java Questions 11 - 20  «Prev  Next»

Java Questions 18 - Class Accessibility and Visibility

  1. Why is default access called package access?

    Answer:
    With default access, the subclass is either in the package or not. If the subclass is not in the package, the package must be imported in order for compilation to occur.

  2. How should you think of default access?

    Answer:
    When you think of default access, think of package restriction.

  3. How should you think about protected access?

    Answer:
    When you think protected, think package and subclasses meaning 1) the subclass must extend the parent 2) the subclass must import that package.

  4. Can a subclass alter a protected member in the superclass?

    Answer:
    No. Protected does not mean that the subclass can treat the protected superclass member as though it were public.

  5. How does a subclass see a protected member?

    Answer:
    The subclass can see the protected member only through inheritance.

  6. How can a subclass access the protected member?

    Answer:
    In this example, an instance variable is a member of the superclass. For a subclass outside the packge the protected member can be accessed only through inheritance and importing the package.

  7. How can you remove the compiler errors if you change the visibility from protected to default?

    Answer:
    A variable in the superclass with access modifier "protected" has visibility in the subclass through 1) inheritance and 2) the subclass imports the package.
    If you change the visibility in the superclass to default, you can remove the compiler errors by using getters and setters in the SuperClass.

  8. What types of modifiers may appear in front of a Java class?

    Answer:
    Only public, abstract, and final may be placed in front of "Class" when declaring a class.

  9. What must be true for a subclass to see an instance variable with default access?

    Answer:
    Just remember that default members are visible to subclasses only if those subclasses are in the same package as the superclass.

  10. Can access modifiers be applied to local variables?

    Answer:
    No. Access modifiers cannot be applied to local variables. The only access modifier you can use for a local variable is final.