Java Questions 18 - Class Accessibility and Visibility
- 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.
- How should you think of default access?
Answer:
When you think of default access, think of package restriction.
- 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.
- 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.
- How does a subclass see a protected member?
Answer:
The subclass can see the protected member only through inheritance.
- 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.
- 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.
- 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.
- 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.
- 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.