Aven Desta
Aven Desta

Reputation: 2443

object oriented programming for security

In OOP, we can assign private, protected and public to variables and methods. I know this has many advantages, but is security one of them? So that unauthorized person must not have access.

Upvotes: 0

Views: 969

Answers (2)

T Tse
T Tse

Reputation: 846

The short answer is "not really". The data is still in the memory, and if you dig around with reflection you can get the content of the fields. Marking fields and methods private is a way to communicate to other programmers: "Hey, this is the internal working of the class, it is prone to change and please don't touch it."

You can get the value of a private field with this:

// suppose we have a class
Person person = new Person("John");
// Field is from java.lang.reflect.Field
Field nameField = Person.class.getDeclaredField("name");
// tell Java to ignore the private modifier
nameField.setAccessible(true);
// now you can "steal" the private field
System.out.println(nameField.get(person));

Unless absolutely necessary, please do not use this is your code, and proceed with extreme caution if you ever use reflection.

Furthermore, even if the field is not accessible by language design, if we are talking security as in an external program scanning the memory, marking fields as private does not hide the data from it. After all.. the data has to be somewhere, right?

Upvotes: 3

Namit Gupta
Namit Gupta

Reputation: 826

This is the principle of encapsulation in oops, which is information hiding. You can use access modifiers to define the visibility of classes, methods and attributes.

You implement this information-hiding mechanism by making your class attributes inaccessible from the outside and by providing getter and/or setter methods for attributes that shall be readable or updatable by other classes.

Upvotes: 0

Related Questions