The BASE for JAVA LEARNING

by PRO FE S S OR


E N C A P S U L A T I O N

AN OBJECT-ORIENTED PILLAR


In Object-Oriented Language, ENCAPSULATION refers to part of a program that is written within a block that has a boundary, and contains:
  • procedures, functions or sub-routines (methods) as well as
  • attributes (variables).
  • In Object-Oriented language that block is represented by a class.

    A class in Java encapsulates methods and attributes.



    Global variables as known in other languages do not exist in Object-Oriented Programming. Variables are contained withint its own class. By the same token, there are no global methods in Object-Oriented languages. All variables and methods are all encapsulated within a class.

    So we can then say that Encapsulation allows any class to contain methods and attributes that can only be used within the class, or accessed by instances (Objects) of that class.


    Why ENCAPSULATION ?


    You probably wonder if we don't have Global Variables, how can a variable can be used or accessed if it's outside its class. An Object which is an instance of a class may refer to variables or objects of another class, and this is what we know as coupling. In Object-oriented language, a high coupling is not desirable. De-coupling then becomes a goal when programming. Keeping the separation among objects when all possible is an ideal situation.

    By encapsulating the program into classes it's easier to keep this separation (de-coupling) among objects and that's why is the most important feature in Object-Oriented Programming.


    Example of JAVA class showing Encapsulation:

    class Capsule
    { // beginning of class

    double kms;
    private final double factor=1.6;
    void convert(double tmpMiles)
    {
    kms = tmpMiles*factor;
    }
    } // ending of class

    // The Capsule class above uses curly braces for its beginning and ending bounds.
    // Attributes "kms" and "factor" and method "convert" are within the class. (Encapsulation)