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":
What private
is good for:
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.
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.
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.
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.
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 Double
s (for instance).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With