Soldier class, with health points 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 ?
The short answer is yes, you succeeded in implementing encapsulation 100% correctly.

Still, I have some smaller problems with your code:

Useless method

I noticed that you have a setter method for the Variable solHealth, which you should rename in my opinion to health. The problem is that the setter is useless as the method has the private access modifier and this method should never be used by the class itself. The only thing that you need to change when deleting this method is that you would have to change the constructor to be like this:

public Soldier() {
    solHealth = 100;
}


This would still follow the concept of encapsulation, as encapsulation is simply a process of wrapping code and data together into a single unit, that allows only minimal manipulation from outer classes.

Comments

If you are commenting your code you can easily implement documentation comments with which you can create JavaDoc pages. This is the standard of how to document methods, classes, and global variables/constants.

Example

/**
 * Set's the soldiers health to the specified value
 *
 * @param health
 */
public void setHealth(int health) {
    // Code here
}