0

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.

2 Answers2

1

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.

Daniel K.
  • 1,326
  • 2
  • 12
  • 18
1

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.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • @Stephan C May i get to know a little more about how reflection work around access permission and in more detail about how to stop that untrusted code? I know its out of the question domain but it is well interesting. – mansi kbchawla Mar 28 '15 at 04:12
  • For example: http://stackoverflow.com/questions/735230/java-reflection-access-protected-field – Stephen C Mar 28 '15 at 04:23