set and get: what they are and how to use these methods correctly

We will learn this lesson of our online Java course the two methods most commonly used by Java programmers: the getters and setters. 

What are they and what are the get and set methods

Get and sets are methods that we often see in Java classes. 
They serve to set and get values from class variables that are defined as 'private', but these method are defined as 'public'. 

Hence arises a natural question: why create methods for accessing variables, if we can access them directly? 
Simple: security issue. 

The variables 'private' can only be accessed from within the class. It's as if they were invisible out of the scope of the class / object. Thus, we avoid other methods, classes or hackers to access data of a particular class, which often can be private data, as is the case of applications for businesses and banks. 

So, how to work with these variables? 
Then it comes the methods questions. Let's allow access to these variables, of course (otherwise there would be no point in using these attributes). 
However, we must have total control over these variables through the methods. 

For example: suppose you have to create an application for a bank, which will limit the number of withdrawals from a customer. 
The values ​​of the balance of that client will be stored in the variable 'balance'. If you give full access to this variable, the client could use uncontrollably services of the bank. 

However, we can create a method in which, each time the client money withdrawal it activates a counter: 

public void setBalance(double value) { 
 balance - = value; 
 counter++; 
} 

In this code snippet, when the user tries to withdraw through the ATM menu, it goes to the method 'setBalance()'. 
So every time he take money, your balance decreases in 'value' and a counter (which is a class variable) is incremented. It is impossible to escape this method! 
Did you understand this beauty? The counter always run! 

We know we have a daily limit for withdrawal, suppose to be three. So let's limit the number of withdrawals: 
public void setBalance(double value) { 
 if (count <= 3) { 
 balance - = amount; 
 counter + +; 
 } else{
 System.out.println ("You have reached the daily limit of withdrawals"); 
  } 
} 

Ready. If you withdraw 3x, the counter will have value 4 (assuming that its initial value is 1), and now it is impossible to draw more, because whenever you try, you will fall into else. 
In the next article we will create an application that simulates a bank. 

How to use getters and setters 

We get to get information. This type of method always returns a value. 
We use set to set values. This type of method usually does not return values, just change variables. 

Using the example of the class "Employee", the last article about Self-reference with this and How to invoking Classes and Objects methods, we have the code: 


getSet.java
public class getSet{
    
    public static void main(String[] args){
        String name = "Neil Peart";
        int ID=2112; 
        double salary = 1000000;
        
        Employee boss = new Employee();
        
        chefe.setNome(name);
        chefe.setID(ID);
        chefe.setSalary(salary);
        
        boss.display();
    }

}


Employee.java
public class Employee {
    private String name;
    private int ID;
    private double salary;
    
    public void display(){
        System.out.printf("Employee %s, ID:%d earn %.2f per month", getName(),getID(),getSalary());
    }
    
    public void setName( String name ){
        this.name = name;
    }
    
    public void setID( int ID ){
        this.ID = ID;
    }
    
    public void setSalary( double salary ){
        this.salary = salary;
    }
    
    public String getName(){
        return this.name;
    }
    
    public int getID(){
        return this.ID;
    }
    
    public double getSalary(){
        return this.salary;
    }
}


How to invoke methods inside the constructor


Another way to initialize variables of an object, is using the methods 'set', straight from the constructor: 

getSet.java
public class getSet{
    
    public static void main(String[] args){
        String name = "Neil Peart";
        int ID=2112; 
        double salary = 1000000;
        
        Conta boss = new Conta();
        
        chefe.setNome(name);
        chefe.setID(ID);
        chefe.setSalary(salary);
        
        boss.display();
        }

}


Employee.java 
public class Employee {
    private String name;
    private int ID;
    private double salary;
    
    public Employee( String name, int ID, double salary){
        setNome(name);
        setID(ID);
        setSalario(salary);
    }

    public void display(){
        System.out.printf("Employee %s, ID:%d earns %.2f per month", getName(),getID(),getSalary());
    }
    
    public void setName( String name ){
        this.name = name;
    }
    
    public void setID( int ID ){
        this.ID = ID;
    }
    
    public void setSalary( double salary ){
        this.salary = salary;
    }
    
    public String getName(){
        return name;
    }
    
    public int getID(){
        return ID;
    }
    
    public double getSalary(){
        return salary;
    }
}

get and set wrong use

What is the difference between change and get the value of a variable directly (if it is public), and get and change the values by getters and setters methods (if it is private)? There is no security, since we can change its value as well as we wish, through the methods in set method. 

Define get and set for all variables, directly, is an example of bad programming habit. Unfortunately it is a technique very common and many programmers, even the most experienced, committed this act useless. 

What are then? When to use? 
Only use set and get when you do something beyond simply changing the value of a variable 'private'. 
There at the beginning of our tutorial, we use the example of counter that limits the number of withdrawals from a customer in an ATM. 

Another example would be a sales application. 
When buying the set or get method automatically sets the value of discount or interest. So this method does something further than change the variable. Thus, your application becomes robust and secure because it is impossible to change the value of the variable is changed without the value of the interest or discount. 

Whenever your set method is of type: 
returnType method(parameterType value){
this.variableName = value;
}

Most likely it is useless. To know when to use is simple: use when doing something besides providing value.

A useful example: 
returnType method(parameterType value){
this.variableName = value * tax;
}; 

Let's train! 

Exercise: ATM in Java - ATM.java 
Create a prototype of an ATM in Java. Earlier, it asks your name and initial value in the account. The program must provide a 4-digit number - account number - to the user (use Random). These data will be used to create an object of class "ATM.java" 

Then, shows a menu with options (this menu should be a method): 
- Bank Statementt: displays the name, account number, balance, and how many operations have been performed 
- Withdraw: get the amount to be withdrawn, reports can be drawn up (can not be negative) and shows the balance 
- Depoist: receives the amount to be deposited and shows the new balance 
- Exit 

This menu appears until the user chooses to exit. The other options are methods that should be part of the "ATM.java" (getters and setters). Note that the user can withdraw at most 5 times per day. 

Click here to see the commented and solved exercise

No comments: