- Java Programming Basics
- Java Tutorial
- Java Environment Setup
- Java Separators
- Java Data Types
- Java Variables
- Java Variable Scope
- Java Type Casting
- Java Operators
- Java Increment Decrement
- Java Left Shift
- Java Right Shift
- Java Bitwise Operators
- Java Ternary Operator
- Java Control Statements
- Java if-else statement
- Java for Loop
- Java while Loop
- Java do-while Loop
- Java switch Statement
- Java break Statement
- Java continue Statement
- Java Popular Topics
- Java Arrays
- Java Multidimensional Array
- Java Strings
- Java Methods
- Java Date and Time
- Java Exception Handling
- Java File Handling
- Java OOP
- Java Classes and Objects
- Java Constructors
- Java Constructor Overloading
- Java Object as Parameter
- Java Returning Objects
- Java Encapsulation
- Java Abstraction
- Java Inheritance
- Java Polymorphism
- Java Packages
- Java Import Statement
- Java Multithreading
- Java Suspend Resume Stop Thread
- Java Programming Examples
- Java Programming Examples
Encapsulation in Java with an example
Encapsulation is the principle of enclosing data and methods into a single unit (i.e., an object) and restricting external access to the object's internal data. This contributes to the object's internal state remaining consistent and its behavior being controllable by a well-defined set of methods.
Java encapsulation example
Consider the following program to be an example of encapsulation in Java. I used proper commenting to aid comprehension, but I also explained the program after the output.
public class MyClass { // Private instance variables can only be accessed by methods within the class private int num; private double bal; // Constructor sets initial values for private instance variables public MyClass(int num, double initialBalance) { this.num = num; this.bal = initialBalance; } // Public getter methods provide controlled access to private instance variables public int getAccountNumber() { return num; } public double getBalance() { return bal; } // Public methods allow balance to be modified, but only through controlled access to private instance variable public void deposit(double amount) { bal += amount; System.out.println("A deposit of $" + amount + " has been made. The new balance is $" + bal); } public void withdraw(double amount) { if (bal < amount) { System.out.println("Insufficient funds."); } else { bal -= amount; System.out.println("A withdrawal of $" + amount + " has been made. The new balance is $" + bal); } } public static void main(String[] args) { // Create an object of MyClass MyClass myObject = new MyClass(123456, 1000.0); // Access private instance variable through public getter method System.out.println("Account number: " + myObject.getAccountNumber() + "\n"); // Modify private instance variable through public method myObject.deposit(500.0); myObject.withdraw(200.0); // Access private instance variable through public getter method System.out.println("\nCurrent balance: $" + myObject.getBalance()); } }
Account number: 123456 A deposit of $500.0 has been made. The new balance is $1500.0 A withdrawal of $200.0 has been made. The new balance is $1300.0 Current balance: $1300.0
Encapsulation is a mechanism that combines data and methods that operate on that data into a single unit, limiting access to the data from outside that unit. Encapsulation is demonstrated in this program by declaring the instance variables "num" and "bal" as "private," which means they can only be accessed within the class.
Public getter methods getAccountNumber() and getBalance() are provided to allow controlled access to these private variables. These methods are accessible from outside the class and return the private variable values.
Similarly, the public methods deposit() and withdraw() allow the balance to be changed, but only with restricted access to the private variable bal. This ensures that the balance can only be changed in accordance with the rules specified in these methods, rather than by modifying the private variable directly.
A MyClass object is created in the main method, and the private variables are accessed and modified using the public getter and modifier methods. This shows how encapsulation allows controlled access to a class's private variables while keeping implementation details hidden from outside the class.
Important information regarding encapsulation in Java
Here are several essential considerations when working with encapsulation in Java:
- Access modifiers (public, private, and protected) are used to control the level of access granted to class members. Encapsulation relies on the use of private access modifiers to limit access to class members to only the class's methods.
- Getters and Setters are public methods that allow controlled access to private class members. You can enforce validation rules, maintain consistency, and ensure that class members are accessed only through controlled methods by using getters and setters.
- Encapsulation benefits include improved data protection and more secure code. It protects internal state, makes code easier to read and maintain, and helps to avoid unwanted changes to the class.
- Encapsulation in inheritance: Subclasses can inherit encapsulation if the superclass members are declared with the protected access modifier.
- Encapsulated variables can be declared as final to prevent them from being changed after initialization.
Advantages of encapsulation in Java
- Encapsulation aids in keeping a class' implementation specifics hidden from other classes. A class's data members are private to other classes and accessible only through its own methods. Data security is provided, and the likelihood of data manipulation by accident is decreased.
- By using encapsulation, the programmer can divide the program into more manageable modules. The development process is made simpler and quicker because these modules can be created and tested independently.
- Encapsulation enables the developer to modify a class's implementation without having an impact on the program's other components. Only the methods that interact with a class need to be updated if its implementation is altered; the rest of the program doesn't need to be changed.
- Encapsulation aids in keeping the code maintainable. It is simpler to maintain the code and fix bugs because a class's data members are hidden from other classes.
Disadvantages of encapsulation in Java
- Encapsulation requires the use of methods to access a class's data members, which can increase program overhead. The program may lag if methods are used.
- Encapsulation may make the program more complex. It might be challenging to comprehend how a class is implemented because its data members are hidden from other classes.
- Access to a class's data members is not entirely barred by encapsulation. A class's private data members can be accessed through public methods, which can cause security problems.
« Previous Tutorial Next Tutorial »