What is Getters and Setters in Java tutorial



In this article we will learn what are 'Getters' and 'Setters' Methods, Before we start let's remove everything from our class activities if you have one and also to our main method we want to have method empty inside the class for the seek of this tutorial

COMPLETE CODES:

class Player{
public int health = 150;
public boolean alive = true;
// this will be generated by compiler in case we don't have any other constructors 
//public Player(){}

public void reduceHealth(int amount){
health -= amount;

}
public void setHealth(int health){
if(health <= 0){
health = 0;
alive = false;
}
this.health = health
}
public int getHealth(){
return health;
}
public boolean isAlive(){return alive;}
}
public void respawn(){
if(!alive){
health = 150;
alive = true;
}
public void printInfo(){
System.out.println("health ="+health + "alive = "+alive);
}
}
}

public class Main{
public static void main(String[] args){
Player player = new Player();
//player.health -= 100;
player.reduceHealth(100);

if(player.health <= 0){
player.health = 0;
player.alive = false;
}
System.out.println("player health =" +player.health);

//player.health -= 100;
player.reduceHealth(100);

if(player.health <= 0){
player.health = 0;
player.alive = false;
}
System.out.println("player health =" +player.health);
player.respawn();
player.printinfo();
}
}

Having public fields in classes is not a good practice, and public fields or variables are prone to many errors that we can generate by accident. 'Getter Method' is a method that gets the value called field That is why it is called 'Getter' It usually starts with the word 'get' or the word 'is' in case of a field being boolean while 'Setter' method sets the value of our fields, that is the reason why it is called 'setters' It starts with the word 'set' So they are just like normal Method does but 'getter' or 'setter' is just a name or naming convention for those methods. In our example we will make 'Player Class' and the player has health and boolean variables that represent if Player is alive, So let's create our class above to our Main Class you can see it above. And we need two fields that will be the "Health" and "boolean alive" let's declare this as 'public int health = 150;' and 'public boolean alive = true;' So when we create the new Player?  alive will be 'true' We can also create a Constructor called
'//public Player(){}' without any arguments and if our constructor is empty we don't need to declare it, because this will be generated by our compiler in case we don't have any other constructors, We can have this empty constructor if we don't create it, Compilers generates it default, No argument constructor for us. This is called default constructor when we don't have any constructors, the compiler generates constructor. If we want 'Player' to lose 'health' we just need to decrement, and every time we decrement health we have to check if Player health = 0, So let's simulate player losing health, in our main method we are going to create a Player player = new Player(); note that this'()' braces calls default constructor generated by our compiler even if we didn't declare that constructor, a constructor will be generated by a compiler. Now if we want to lose 'health' we need to type something like 'player.health -= 100;' 

so a player will be lost 100 health and now we need to check if the field is lower or equal to zero and set player alive to false like the code below

 if(player.health < = 0){
player.health = 0;
}

since we don't want to have health that is less than zero. And when a field is zero that means the player is not alive anymore so we can type 'player.alive =false;' And now let's print player health with 'System.out.println("player health =" +player.health);'. Again if we re-use '100'  like player.health -= 100; We have to duplicate code and check the health so we again have to copy-paste the 'if statements' to have the same logic and to keep 'health = 0', and our alive flag to 'false', now if we run this code you will see that the player.health = 0 and our alive will be set to 'false', But first it will print player health = 50; since our player health starts with 150 then it prints player health = 0; So every time we decrement health we have to check if player health = 0 and that these duplicates code and logic all our logic is spread all around the code, Now imagine that other classes need to use 'Player class' and they also have to reduce the health, Then again we have to duplicate code and again we need to write the same 'if-statement' to check and to keep health at zero. So the solution is to add a method that reduces health, That will check health for us and set Flagged boolean to 'false' or our variable 'alive = false', The problem is the health still goes below zero, if we want to keep it minimum zero then we need to add another method. Let's first add our 'Method reduces health' this method will just reduce health and that method will go to our 'Player class' like the code below

public void reduceHealth(int amount){
health -= amount;} 

We will just reduce health so 'health -= amount;'  and now we can just set alive = false; instead of duplicating the if(){} statement we are setting health to the amount that we are re-using, so instead of using //player.health -=100; we can use 'player.reduceHealth(100); But still, we didn't get rid of our if statement then we will type player.reduceHealth(100); to our second duplicate code of if-statement. We still have duplicated if- statement. So now this is where the 'setter' method is really helpful. We can add additional checks and additional logic to the 'setter'  method. To Player class we will add method  'setHealth()' that method will update method health field or variable and it will make sure it never goes below zero, So we can now make the fields as 'private int health = 150;' and 'private boolean alive = true;' we can then delete the if(){} statements and his duplicates. Now we need to write those 'setter' method like

public void setHealth(int newHealth){
if(newHealth <= 0){
newHealth = 0;
alive = false;
}
}
and now we can use that if statement so we need to check newHealth < = 0 then newHealth = 0; we've just reset it to zero And later we will use this new health variable or parameter to set our health variable to the value of new health since health is zero alive also will be 'alive =false' after the if-statement we can say health = newHealth; here we don't need 'this' keyword, But if we refactor or rename parameters to 'health' then automatically IDE  will insert 'this. health = health' because it is required when we have a parameter with the same name as our variable. So notice just when we click on the parameter it highlights all the usages of that parameter, When we click on health which is variable or field inside of our class it highlights where these fields are used. And now to create a 'Getters' we just need to return our 'health' because we want to print that value in our main method then Type 'public int getHealth(){return health;}' We are just returning the value of the health, Another method that we need is to print info about the internal state of the player and that is 'health' and 'alive' so now that we have a getter and private fields we also need a getter for our 'boolean alive' to check if a player is still alive, in this case, we don't need a setter for alive. We can say that alive is a read-only field since we can't change it from outside. field health is a read-write field since we can change it from outside. now let's add a getter for 'alive' since alive is boolean then getter start with 'isAlive' keyword like 'public boolean isAlive(){return alive;}' and we need to return alive. Now we need to use this setter so in our 'reduceHealth()' method instead of using fields directly we can call setHealth(health - amount); and then our setHealth() get calls and this 'int health' parameter will be equal to (health -amount); and if that difference is less than zero then parameter will be set to zero and our health will again be set to zero. if parameter health < = 0  then if(health<0){health =0;alive=false;} will not execute and we will just set our field to health, So this way with setter's we can add additional logic and control our player. Another useful method would be to respawn our player that method respawn player but only if he is not alive so let's add method respawn like public void respawn(){} And here we need to check if a player is not alive then respawn player so if(!alive){health = 150; alive = true;} Instead of creating the same if statement all over the code we can wrap it inside the method respawn and use the method itself, Now let's fix our main method first we are reducing health and now we want to print player health so we can use System.out.println("player health =" + player.getHealth() + "alive = "+player.isAlive()); now this is a bit too long to type, so instead of type  we can create in player  a useful method that will print these for us so create method

  'public void printInfo(){
System.out.println("health ="+health + "alive = "+alive);
}'  
 And in this method, we can paste System.out.println("health ="+health + "alive = "+alive);  in the main method we can call the 'printInfo()' directly so this setHealth() helps us to avoid duplicate code, you can see how with private fields we have more control over the code it can happen by accident somebody set's alive= false even when a player is alive and a player has more health with the additional logic in setter we are controlling when a player gets dies so with this setter we are controlling alive variable and alive variable is a read-only we can't see it from outside of this class, so with making fields private and using getters and setters there are many advantages which we will see in the next few lessons but first let's add some more code to print health and alive and let's respawn our player so in the main method after printInfo(); call method player.respawn(); then player.printInfo(); Now lets run the code and here you will notice that health = 50, alive = true and in the next line we will see health = 0; alive = false; and in the third line will be health = 150, alive = true;












Post a Comment

0 Comments