Java Quick Reference
  Language Fundamentals
  Operators and Assignments
  Flow Control and Exceptions
  Declarations and Access Control
  Garbage Collection
  Overloading and Overriding
  Threads
  The java.lang Package
  The java.util Package
  The java.awt Package
  The java.io Package
  References
  Miscellaneous Notes
  Tips & Traps
  Mock Exams

Overloading, Overriding, Runtime Types and Object Orientation - Encapsulation

  • objects have both state (details about itself) and behaviour (what it can do)
  • a software object maintains information about its state in variables
  • what an object can do, its behaviour, is implemented with methods
  • in Object-oriented programming (OOPs), an object is encapsulated when its variables and methods are combined into a single component
  • encapsulation also involves access to an object; its interface
  • a tightly encapsulated object hides all it's variables and provides public accessor methods ie the only way you can use the object is by invoking it's public methods
"Hiding data behind methods so that it is inaccessible to other objects is the fundamental basis of data encapsulation." (JPL pg.12)
  • encapsulation has two main benefits: (VA pg44)
    1. modularity
    2. maintainablity

Modularity

  • because the object encapsulates all it's variables and the methods needed to make it work, it is a self-contained entity that can be maintained independently of other objects

Maintainability

  • because the object hides it's implementation details behind a well-defined interface, the details can be changed without affecting other parts of the program

Example

class TestBook{
  public static void main(String[] args) {
    Book b1 = new Book();
    System.out.println(b1);
        
//  b1.title = "Java Programming Language";     
//  b1.author = "Ken Arnold and James Gosling"; 

   // must use accessor methods
   b1.setTitle("The Java Programming Language: Second Edition");
   b1.setAuthor("Ken Arnold and James Gosling");

// System.out.println(b1.title, b1.author);    
        
   System.out.println(" Title: " + b1.getTitle() );
   System.out.println("Author: " + b1.getAuthor() );        
    }
}
  • In the example code, the instance variables title and author are private; they can only be accessed by their gettor and settor methods
  • any attempt to directly set or get the variables produces a compile error

Example Code

Encapsulation Polymorphism isA/hasA Overloading Overriding Field Variables
Initialization Top-level Classes Inner Classes Static Nested Classes Local Classes Anonymous Classes