Recently I completed the encapsulation lesson and I made a simple android app implementing encapsulation, I had difficulties understanding encapsulation.
My Soldier class:
public class Soldier {
//Start of the class.
private int solHealth;
/* Soldier class constructor with the code to set the soldier health to 100
* when ever we create a soldier object.*/
public Soldier(){
this.setSolHealth(100);
}
//setter method with the parameter to set the solHealth variable.
private void setSolHealth(int solHealth) {
this.solHealth = solHealth;
}
//getter method to get the solHealth value.
public int getSolHealth(){
return this.solHealth;
}
//Main method to heal the soldier by 25 every time this method is called.
public int heal(){
this.solHealth += 25;
//Log used for debugging.
Log.i("Info", "" + solHealth);
return solHealth;
}
//Main method to injure the soldier by 25 every time this method is called.
public int injure(){
this.solHealth -= 25;
//Log used for debugging.
Log.i("Info", "" + solHealth);
return solHealth;
}
//End of the class.
}
I created a soldier object in the MainActivity class and used it to access getSolHealth(), heal(), and injure() methods, and to manipulate solHealth values when the button is pressed.
Did I succeed implementing encapsulation correctly ?
solHealth
and the getter and setter of it to justhealth
as it's quite obvious you are referring to the soldier's health \$\endgroup\$getSolHealth
tohealth
but togetHealth
(the same applies to the setter) \$\endgroup\$