Field Encapsulation

In computer programming, field encapsulation involves providing methods that can be used to read/write to/from the field rather than accessing the field directly. Sometimes these accessor methods are called getX and setX (where X is the field's name), which are also known as mutator methods. Usually the accessor methods have public visibility while the field being encapsulated is given private visibility - this allows a programmer to restrict what actions another user of the code can perform. Compare the following Java class in which the name field has not been encapsulated:

public class NormalFieldClass { public String name; public static void main(String args) { NormalFieldClass example1 = new NormalFieldClass; example1.name = "myName"; System.out.println("My name is " + example1.name); } }

with the same example using encapsulation:

public class EncapsulatedFieldClass { private String name; public String getName { return name; } public void setName(String newName) { name = newName; } public static void main(String args) { EncapsulatedFieldClass example1 = new EncapsulatedFieldClass; example1.setName("myName"); System.out.println("My name is " + example1.getName); } }

In the first example a user is free to use the public name variable however they see fit - in the second however the writer of the class retains control over how the private name variable is read and written by only permitting access to the field via its getName and setName methods.

Read more about Field Encapsulation:  Advantages, Disadvantages

Famous quotes containing the word field:

    The little toy dog is covered with dust,
    But sturdy and stanch he stands;
    And the little toy soldier is red with rust,
    And the musket moulds in his hands.
    Time was when the little toy dog was new,
    And the soldier was passing fair;
    And that was the time when our Little Boy Blue
    Kissed them and put them there.
    —Eugene Field (1850–1895)