Access Methods in Java

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?

+4
source share
8 answers

Try this Golden Rule of Object Oriented Programming.

1. Create private instance variables.

2. Create public recipients and setters to access this instance variable.

3. This methodology is called Encapsulation . Although Encapsulation can be used in different ways that matter in Design Templates , for example, those that continue to change must be encapsulated in an abstract class or interfaces.

4. Well, back to Getter and Setter ....

Getter and Setter helps verify input to an instance variable.

For example: Suppose I have a way to set the age of a dog. Now age can be negative. If I do not have a setter method, then I cannot confirm the input age.

 private int age; public void setDogAge(int age){ if (age>0){ this.age = age; } else{ System.out.println("Please Enter a Valid Age"); } } 
+5
source

When using trivial access methods, there is no difference other than style, but you can also execute code with them, for example:

 public void setName(String name) { if (name == null) { throw new IllegalArgumentException("Name may not be null"); } this.name = name; } 

You can also return copies from the getter, thereby protecting your data:

 private List<String> middleNames; public List<String> getMiddleNames() { return new ArrayList<String>(middleNames); // return a copy // The caller can modify the returned list without affecting your data } 

These are just two simple examples, but there are unlimited examples of using access methods.

It is better to follow a consistent style, so we always use getters / setters - so the code that can be executed can be executed if necessary.

+7
source

The advantage of using seters ans getters is that you can enable rules for lazy initialization, validation, etc. In addition, if you need to implement Java Beans complaint code, you must follow these rules.

Java Beans spec

+2
source

If your code never changes, you are right - there is no difference.

However, the code changes a lot. What happens if you need to keep track of who changed your name?

You will need to have a boolean in the Account class that changes to true when the name field changes.

So now you need to go through each source file and put

myAccount.nameChanged = true' under each

myAccount.name = whatever;

So, you start code duplication, and the likelihood of errors increases. What happens if I miss a name change?

The best way to counteract this is to have member variables classified as private .

Your setName code will look something like this:

 public void setName(String newName) { name = newName; nameChanged = true; } 

And you do not need to worry about mistakes!

+1
source

This is called Encapsulation when you declare some private instance variables and declare a public getter and setter method to access and change the value of the instance variables.

If you use these getter and setter methods to access / set instance variables, then it ensures that your program does not work if the developer changes the instance variable names.

For example, in the current version, you use the name and address, the balance of instance variables and access them without getter and setter methods, such as myAccount.setName("Blah blah"); but what if the developer of the next version changes the name of the instance variable from name to userName in which case the user program will break, but if you use getter and setter it will not break, since the developer will not change the name of the getter and setter method (according to the basics of OOPS )

+1
source

In fact, this does not interfere and there is no difference until you change the access modifiers for the getter / setter methods or add additional logic to them. The latter is not always a good idea, but sometimes it helps, for example, updating a name should force updating some cached value or performing some checks as a result. Using getters / seters is good practice and is used in several approaches, such as POJO and JavaBeans, but if you are not going to add custom logic to getters / seters and are not going to use these approaches, you will be satisfied with the use of direct access to fields.

One thing I would like to mention. The use of getters / setters that you can provide is calculated in runtime fields that are not permanently stored in the object. For example, your Account object has a date of birth, and you need to get the age from it.

0
source

You can always develop an application without using the getter and setter methods. As you explained. But using getter and setter is best practice because private / public access modifiers provide you with encapsulation, which is an OOPS function. You can always write your program without using OOPS functions, such as encapsulation, abstraction, inheritance ... but if you write large applications without using, you will have problems with maintenance and will soon understand the importance of these functions.

0
source

The java keyword "private" before each class account prohibits a direct link to this field. If you put myAccount.name = "whatever" in UseAccount, you will get the error message: "the name has private access to Account". Instead of referencing myAccount.name, the UseAccount programmer must call myAccount.setName or myAccount.getName. These methods are called access methods because they provide access to the fields of account classes.

0
source

All Articles