Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are private members really more "secure" in Java?

Tags:

java

oop

Learning Java I was sometimes taught to use the private access modifier so as not to expose "sensitive information" to other classes, as if this could open a legitimate security hole. But I've never encountered a situation in which restricting member visibility was more than a convenience for modelling a program in an object-oriented fashion.

Are private fields and functions in Java classes actually more "secure" than otherwise?


EDIT -- Compilation of best answers.

Why private does not mean "secure":

  • decompilers allow static look at bytecode
  • reflection library allows runtime access to private members

What private is good for:

  • maintainability of code due to forcing method-level access
  • modularity of code by hiding implementation details
like image 786
calebds Avatar asked Feb 08 '12 21:02

calebds


People also ask

Is private more secure than protected?

If you are going to use the functions everywhere in the program you should use public. If you want to use them only when they are needed by the classes that extends that class you have to use protected. If you want to use it only inside that class you should use private.

How Java is highly secure?

Java is secure due to the following reasons: Java programs run inside a virtual machine which is known as a sandbox. Java does not support explicit pointer. Byte-code verifier checks the code fragments for illegal code that can violate access right to object.

Why use private instead of public in Java?

public means you can access it anywhere while private means you can only access it inside its own class. Just to note all private, protected, or public modifiers are not applicable to local variables in Java.

Why is private important in Java?

Making a variable private "protects" its value when the code runs. At this level, we are not concerned with protecting it from other programmers changing the code itself. The point of so-called "data hiding" is to keep internal data hidden from other classes which use the class.


1 Answers

I've never heard of it -- in any serious sense -- as a security issue. I mean, decompilers work. You can use them to figure out what's going on inside the bytecode.

Having private members is a maintainability issue. If I only give you method-level access to my internals, then my only responsibility is to ensure that my API methods continue to work. I'm not locked into using a Double versus a BigDecimal on the insides, so long as my methods continue to return Doubles (for instance).

like image 171
Jim Kiley Avatar answered Sep 28 '22 00:09

Jim Kiley