mansi kbchawla
mansi kbchawla

Reputation: 69

How packages provide security for classes and interfaces?

While reading about packages in java i came across an imp feature of packages in

java which says

To provide security to the classes and interfaces.So that Outside persons can't access it directly but how? I havent used this feature and i am curious to know about it.

Upvotes: 0

Views: 470

Answers (2)

Stephen C
Stephen C

Reputation: 718836

Packages don't provide security in any meaningful sense. However, they do help to support modularization via "package private" access:

package com.example;

public class Example {
    int someMethod() { ... }
}

The access for someMethod is package private, which means that it is only visible to other classes in the com.example package. You can control the visibility of fields, classes and interfaces in the same way.

Note that this is NOT a credible security mechanism for most Java applications. It is simple for an application to use reflection to work around most (if not all) access restrictions based on access modifiers. The only way to stop that is to run untrusted code in a security sandbox that disables the use of the reflection APIs.

Upvotes: 1

Daniel K.
Daniel K.

Reputation: 1566

The question was vague, but this is a way to provide security using packages...

If a variable is protected, only subclasses of it, and classes in the same package can access it. This can be useful if you want to add security as you can only make files that you add to your package be able to access the variable in your class.

Example:

Say if I a bank program. I have a protected variable called balance. If the variable was public someone could crete a program that could access the class and change balance however they pleased. But since its protected, only the files I put in my bank package can access the variable to change it.

Upvotes: 1

Related Questions