Skip to content

Encapsulation

Keyhan Hadjari edited this page Sep 16, 2016 · 4 revisions

When Creating a POJO class you usually have something like:

public class Person{
    String name;
    int age;
}

public class PersonFactory {
    public Person create() {
        Person person = new Person();
        person.age = 5555; //bad input
        person.name = o45fi0+i+sd0; //bad input
        return person;
    }
}

To fix this problems we encapsulate data as below

public class Person{
    private String name;
    private int age;

    public setName(String name) {
        //First validate that only alphabetic signs are in the name, if not throw exception
        this.name = name;
    }

    public setAge(int age) {
        if(age <0 && age > 130) {
             throw new FormatException("Age cannot be right");
        }
        this.age = age;
    }

}

public class PersonFactory {
    public Person create() {
        Person person = new Person();
        person.setAge(5555); //EXCEPTION
        person.setName(o45fi0+i+sd0); //bad input EXCEPTION
    }
}

Immutibility by Encapsulation:

  • Making a class immutable. By not providing getter to its fields, that are all private.
    • Be careful so that the field is immutable or is a basic type.

Clone this wiki locally