Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to make instance variables private?

Tags:

java

oop

I'm trying to understand the usage for getter/setter methods in a class. Let's say we have a class called A with some public instance variables followed by a constructor with parameters where arguments were passed from another class(main) to it. Inside the constructor we let those instance variables equal what was passed.

Now if this class were to be used by another programmer, nothing would stop them from directly accessing/changing the instance variables to something that isn't valid. By making the instance variables private we can eliminate access to those variables. However if we wanted to have those instance variables updated/changed indirectly or under some specific condition or perhaps just letting the person have access to the instance variable, we would create a getter/setter pair for this purpose.

Benefits?:
1.Change instance variable only under certain valid reasons under the set() method
2.So that we can show what the instance variable actually is without giving the programmer who is using this class the ability to change it.

Is this a correct interpretation?

like image 534
BubbleTree Avatar asked Nov 26 '25 15:11

BubbleTree


1 Answers

Encapsulation – refers to keeping all the related members (variables and methods) together in an object. Specifying member variables as private can hide the variables and methods. Objects should hide their inner workings from the outside view. Good encapsulation improves code modularity by preventing objects interacting with each other in an unexpected way, which in turn makes future development and refactoring efforts easy.

enter image description here

Being able to encapsulate members of a class is important for security and integrity. We can protect variables from unacceptable values. The sample code above describes how encapsulation can be used to protect the MyMarks object from having negative values. Any modification to member variable vmarks can only be carried out through the setter method setMarks(int mark). This prevents the object MyMarks from having any negative values by throwing an exception.

like image 69
Maxim Shoustin Avatar answered Nov 29 '25 04:11

Maxim Shoustin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!