Jump to content

Data encapsulation

From Wikipedia, the free encyclopedia

This is an old revision of this page, as edited by BenAveling (talk | contribs) at 23:00, 2 March 2007 (Moved. Now make generic.). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

Most programming languages allow the programmer to encapsulate data. Encapsulation protects data from inappropriate access by other parts of the same program, in order to encourage certain good programing practices.


Example

public class PrivateTest {
    private int x = 10; // we want to protect x
    public int y = 11;  // we don't mind exposing y

    public int getX() {
        return x;
    }
}

public class NoseyNeighbour {
    public int f(PrivateTest p) {
        print(p.x);      // Error, cannot access x
        print(p.getX()); // This is OK
        print(p.y);      // This is OK
        p.y=12;          // Even this is OK.
    }
}

The variable x can not be accessed outside of the class PrivateTest. In other words only an instance of PrivateTest may modify or look at the variable x.