Encapsulation (Cont.)


Why Encapsulation?
Get and Set
The private variables can only be accessed within the same class (an outside class has no access to it). However, it is possible to access them if we provide public getter and setter methods. The get method returns the variable value, and the set method sets the value. Syntax for both is that they start with either get or set, followed by the name of the variable, with the first letter in upper case:

GetnSet.java (get and set)
public class GetnSet {
  String name = "Sponge Bob";

  public static void main( String[ ] args ) {
    // Creates a Person object.
    Person myObj = new Person( );
    // Sets the value of the name variable.
    myObj.setName( args[0] );
    // Gets the value of the name variable.
    System.out.println( myObj.getName( ) );
  }
}

class Person {
  // private = restricted access
  private String name = "Digi Mon";
  // Getter
  public String getName( ) { return name; }
  // Setter
  public void setName( String newName ) { name = newName; }
}
shell> java GetnSet  

Output:           Result: