So, I have a question about the "setter" and "getter" methods and how useful or not they are.
Let's say I just write a very basic program, such as:
public class Account { String name; String address; double balance; }
Then, say, I write another class that uses this class "Account", for example:
class UseAccount { public static void main(String[] args) { Account myAccount = new Account(); Account yourAccount = new Account(); myAccount.name = "Blah blah" } }
etc. etc.
When I write myAccount.name = "Blah blah" , I change the value of the variable "name" in the class "Account". I am free to do this as many times as I like with code written as it is. However, it occurred to me that it is better to use the variables in the Account class, and then use the setter and getter methods. Therefore, if I write the following:
public class Account { private String name; private String address; private String balance; public void setName(String n) { name = n; } public String getName() { return name; } }
I can still change the value of the "name" variable by simply creating another class that has something like:
class UseAccount { public static void main(String[] args) { Account myAccount = new Account(); myAccount.setName("Blah blah"); } }
I do not understand how the use of this method is any other or should prevent people from changing the value of the private field. Any help?
source share