Top
Previous Next
Java's Object Orientation, I/O CS 161 - Java

Encapsulation

  • supports modularity - an object can be written and maintained independently of other objects.

  • information hiding - objects have public methods that they expose for other objects to use. These methods permit other objects to send "messages" to it. Private variables and methods of the object are implementation details that can be changed at any time without affecting other objects.

  • Classes should expose to the outside just the methods needed to make the object do the things it is designed to do;

  • None of the internal details related to the particular implementation of the class should be visible to the outside.
    Source: examples/Employee.java

    
    

    /** A class that encapsulates information about and messages to
    ** send to Employee objects.
    **/
    public class Employee {
     
    public static void main (String [] args) {
    // create a single instance of the Employee class,
    Employee anEmp = new Employee("Joe Student");
     
    // assign a name and a salary value (any value), using the constructor
    // and the setSalary() methods
    anEmp.setSalary(50000.);
     
    // Access the current salary value (using the getSalary() method)
    double current = anEmp.getSalary();
     
    // and increase the Employee's salary by 10% using the
    // setSalary method again.
    current = current + (current * .1);
    anEmp.setSalary(current);
     
    // then have the Employee object identify itself and it's
    // current salary value.
    System.out.println(anEmp);
    }
     
    private String name;
    private double salary;
    private Employee boss;
     
    /** a public constructor for the class that will insure that Employee
    objects always have a name field
    **/
    public Employee( String empName) {
    name = empName;
    }
     
    public String getName() {
    return name;
    }
     
    /** a method to set an Employee object's salary field
    **/
    public void setSalary( double value ) {
    salary = value;
    }
     
    /** a method to get an Employee object's current salary field value
    **/
    public double getSalary( ) {
    return salary;
    }
     
    /** a method to set an Employee object's field referencing another
    Employee object
    **/
    public void setBoss ( Employee boss ) {
    this.boss = boss;
    }
     
    /** a method to return a String identifying the field contents of an
    Employee
    **/
    public String toString() {
    return name + " salary:" + salary;
    }
    }


  • Top
    Previous Next
    jwd