You want a class to have access to members of another class in the same package. Which is the most restrictive access that accomplishes this objective?

  1. public

  2. private

  3. protected

  4. default access


Correct Option: D
Explanation:
  • Public access is the least restrictive access modifier. Members with public access can be accessed from anywhere in the program.
  • Private access is the most restrictive access modifier. Members with private access can only be accessed from within the class in which they are declared.
  • Protected access is a middle ground between public and private access. Members with protected access can be accessed from within the class in which they are declared, and from subclasses of that class.
  • Default access is also known as package-private access. Members with default access can be accessed from any class in the same package.

So, the most restrictive access modifier that allows a class in the same package to access members of another class in the same package is Default.

Here is a table that summarizes the different access modifiers in Java:

Access modifier Visibility
public Anywhere in the program
private Only within the class in which it is declared
protected Within the class in which it is declared, and from subclasses of that class
default Only within the same package

The difference between protected and default access is that protected allows access from subclasses in other packages, while default does not. For example, if you have a class Animal in package A, and a class Dog in package B that extends Animal, then the class Dog can access the protected members of Animal, but not the default members. However, if you have a class Cat in package A that extends Animal, then the class Cat can access both the protected and the default members of Animal.

More quiz related to this question.

Find more quizzes: