Encapsulation

Hello guys, let me introduced you with one of the topics I was struggling while in High School. The term is encapsulation , do not let the name intimidate you. We will break it apart, and make it digestible for anyone to understand it.

Encapsulation : Means Hiding the internal details or mechanics of how an object does something

Related image


* The need for encapsulation is to make sure our ” private data its safe
* Since the only way that we will be able to access our data will be through methods
* public = anyone can access the variable

//com.collabera.encapsulation;
// (Project name here)

class EncapsulationDemo{

    // encapsulation = binding data with methods

     // Private variables
    private Integer moneyOwed;
    // We make sure variables are always private
    private String name;


    

  • Notice the private variables , We will sometimes encounter private data the the user shouldn’t necessarily have access to.
// Getter, and setter methods that will access our private variables.

    public Integer getMoneyOwed() {
        return moneyOwed;
    }

    public void setTotal(Integer moneyOwed) {
        this.moneyOwed = moneyOwed;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
  • The private variables are bonded with the getter , and setter methods.
  • By binding our private data to our methods we create a more secure program.
public class Ex {

    public static void main(String[] args) {

        EncapsulationDemo demoObject1 = new EncapsulationDemo();
        demoObject1.setTotal(5);
        demoObject1.setName("Dan");

System.out.println(demoObject1.getMoneyOwed());
System.out.println(demoObject1.getName());

    }

}
  • To be able to call those private variables , we need to call our get method
  • Encapsulation it’s really simple !

3 comments

  1. Lee Angioletti's avatar
    Lee Angioletti · August 7, 2019

    Reblogged this on Learning Full Stack Development.

    Like

  2. gregreed56's avatar
    gregreed56 · August 7, 2019

    Reblogged this on Gregory Reed.

    Like

  3. Lee Angioletti's avatar
    Lee Angioletti · August 8, 2019

    Well done, Daniel. The example made it clear as to what encapsulation is.

    Liked by 1 person

Leave a comment