Encapsulation

Special Java privacy attributes

Java has a special way to keep information in objects safe from people who are not supposed to access field information. This process is called Encapsulation, and it is done by using the private tag. This is seen in our previous example below:

public class Camera {

private int lensSize;

private int pictureWidth, pictureLength; // in pixels

public void takePicture() {

// Takes a picture!

}

public void takeVideo(int videoLength) {

// Takes a video with the specified length

}

}

The class's fields are all protected using the private modifier which declares that all methods outside the class will not be able to access or modify the value of the attribute. This means that the following code segment will not work on the above example:

public class Driver {

public static void main(String[] args) {

// Creates a new Camera object with the dimensions

Camera myCamera = new Camera(5, 300, 500);


// Both will not work due to encapsulation

myCamera.lensSize = 1000;

System.out.println(myCamera.pictureWidth);

}

}

If we would like our users to be able to view the field value but not modify it, we can implement a "get" method. This would simply return the value of the field to the user such as the example below:

public class Camera {

private int lensSize;

private int pictureWidth, pictureLength; // in pixels

public void takePicture() {

// Takes a picture!

}

public void takeVideo(int videoLength) {

// Takes a video with the specified length

}


public int getLensSize() {

return lensSize;

}

}

We can also allow our users to modify the field value but not view the value of the field by implemening a "set" method:

public class Camera {

private int lensSize;

private int pictureWidth, pictureLength; // in pixels

public void takePicture() {

// Takes a picture!

}

public void takeVideo(int videoLength) {

// Takes a video with the specified length

}


public void setLensSize(int newSize) {

lensSize = newSize;

}

}