LINKS

Java Tutor Homepage

Java Applications and Components

Java Applets and Components

Java Frequently Asked Questions:
    1. What is Inheritance?
    2. What is Polymorphism?
    3. What is Encapsulation?
    4. Avoiding the Divide by Zero Error
    5. Public Classes in Java Source Files
    6. The Import Statement in Java
    7. Classes with Default Access
    8. What are Local Variables?
    9. What is an Abstract Method?
    10. Data Structures
    11. What is Autoboxing and Auto-Unboxing?
    12. What is multithreading?
    13. What are Threads?
    14. Thread States
    15. What is the Purpose of Synchronization?
    16. Thread Interaction
    17. Can You Start a Thread Twice?

Java FAQ 3 - What is Encapsulation?

Encapsulation is a programming practice that is designed to make it impossible to access the variables of a class directly; rather then directly accessing the variables of a class, you must use “set” and “get” methods for each variable. The reason for the use of encapsulation is that it is very easy to make a mistake in code which tries to get the value of a variable or while trying to set the value of a variable. The “set” methods which you call to set the value of the variable should contain code which will prevent an incorrect value from being set. The “get” method simply gives you a copy of the value in variable rather then the actual value in the variable.

To Make a Program Well Encapsulated:

Declare all instance variables of classes as private, and use “set” and “get” methods (even within the class itself) to set the value of the variable and to get the value of the variable. Also be careful with declaring methods as public or private. If the method does something which only other methods within the class should be able to do, declare it as private.