123k views
1 vote
What modifier should you use on a class so that a class in the same package can access it but a class in a different package cannot access it?

A. Public
B. Private
C. Protected
D. Use the default modifier.

User Ralitsa
by
8.2k points

1 Answer

6 votes

Final answer:

To allow access to a class from within the same package but prevent access from a different package, do not specify any access modifier; this applies the default (package-private) modifier to the class.

Step-by-step explanation:

To ensure that a class in the same package can access a class while a class in a different package cannot, you should use the default modifier. This means you do not explicitly specify any access modifier, which is also known as package-private access. In Java, if a class is declared without any modifier (i.e., public, private, or protected), it is accessible by any class within the same package, but not accessible by classes in other packages.

Here's how you might declare a class with default access:

class MyClass {
// Class contents
}

With this declaration, MyClass would be accessible only within its own package.

User Zhen Zhang
by
7.9k points