I want to know when to use get and set methods(getName,setName ) in my class and when simple classVariable.name = ""
instead а = classVariable.getName()
Here is example of class using set and get methods
public class ClassExampe { String name; String course; public String getName ( ) { return name; } public void setName (String studentName) { name = studentName; } public String getCourse ( ) { return course; } public void setCourse (String studentCourse) { course = studentCourse; } }
Thanks
Getters and setters are used to protect your data, particularly when creating classes. For each instance variable, a getter method returns its value while a setter method sets or updates its value. Given this, getters and setters are also known as accessors and mutators, respectively.
Python | set() method set() method is used to convert any of the iterable to sequence of iterable elements with distinct elements, commonly called Set. Parameters : Any iterable sequence like list, tuple or dictionary. Returns : An empty set if no element is passed.
getters and setter can have validation in them, fields can't. using getter you can get subclass of wanted class. getters and setters are polymorphic, fields aren't. debugging can be much simpler, because breakpoint can be placed inside one method not near many references of that given field.
The reason for declaring the getters and setters private is to make the corresponding part of the object's abstract state (i.e. the values) private. That's largely independent of the decision to use getters and setters or not to hide the implementation types, prevent direct access, etc.
As a rule of thumb:
use the variables directly from the same class (actually from the same .java file, so inner classes are ok too), use Getters / Setters from other classes.
The simple rule is: never use direct access (except, of course, when referring to them from inside the class).
Even if this does not happen that you need any of these, it is not unlikely. And if you start with field access, it will be harder to change.
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