207k views
5 votes
If a variable should be directly accessible from subclass, which access modifier should be used?

a. public
b. protected
c. private
d. package visibility

User Kimbley
by
8.6k points

1 Answer

5 votes

Final answer:

To allow direct access to a variable from a subclass, the protected access modifier should be used. It ensures that subclasses and classes in the same package can access the variable, maintaining good encapsulation practices.

Step-by-step explanation:

If a variable should be directly accessible from a subclass, the access modifier that should be used is protected. Public access would also make the variable accessible, but it allows access from any other class, which might not be desirable for encapsulation.

Private access restricts the variable to the class itself and package visibility (default access in Java), would limit access to classes within the same package. Therefore, protected is the best option, as it allows access from subclasses and from classes in the same package without making it available globally.

User Yawar Murtaza
by
8.4k points