Java OOPs...Encapsulation!

Java OOPs...Encapsulation!

Consider a real-life example of your bank account, your account balance is private—you wouldn’t want anyone to directly change it. However, you’d welcome someone depositing money into your account. This demonstrates the concept of data privacy.

Here, your account balance represents private data, while the deposit method is a public method that allows controlled access to modify the balance. Similarly, the withdraw method is also a public method, provides another controlled way to interact with your balance.

Now, Encapsulation by definition - "Encapsulation describes the ability of an object to hide its data and methods from the rest of the world and is one of the fundamental principles of object-oriented programming"

It also enables you to restrict access only to those features of an object that are declared public. All other fields and methods are private and can be used for internal object processing.

Take this example
package Encapsualtions;
public class BankAccount {
	// balance should be private, should not accessible by script or APIs.
	private double balance;
	// Now initialize balance using constructor
	public BankAccount(double initialBalance) {
		this.balance = initialBalance;
	}
	// Public method to check balance
	public double getBalance() {
		return balance;
	}
	public void Deposit(double amount) {
		if (amount > 0) {
			balance = balance + amount;
		} else {
			System.out.println("You don't have sufficient amount");
		}

	}
	public void Withdraw(double amount) {
		if (amount > 0 && amount <= amount) {
			balance = balance - amount;

		} else {
			System.out.println("Enter another amount for your withdrawal");
		}

	}

	public static void main(String[] args) {

		BankAccount bankaccount = new BankAccount(1000);
		bankaccount.Deposit(1);
		bankaccount.Withdraw(9);
		
		System.out.println("Your Available amount is ?:" + bankaccount.getBalance());
	}
}
//output
Your Available amount is ?:992.0        

Why Constructor?

If there were no constructor, you would need to explicitly set the balance using a separate method, like

BankAccount bankaccount = new BankAccount();

bankaccount.Deposit(5000); // Set initial balance

The constructor simplifies and enforces proper initialization of the BankAccount object, ensuring it starts with a valid state (balance initialized). This is a key principle of object-oriented programming and encapsulation.

Why 'this'?

In the constructor, this is used to access the instance variable of the object being constructed, using 'this' explicitly specifies that you're assigning the value to the instance variable ie- initialBalance.

Take another Example
package Encapsualtions;
public class BankAccount1 {
	    // Private data members
	    private String AcntNumber;
	    private String AcntHolder;
	    private double balance;

	    // Constructor to initialize data members
	    public BankAccount1(String accountNumber, String accountHolderName, double initialBalance) {
	        this.AcntNumber = accountNumber;
	        this.AcntHolder = accountHolderName;
	        this.balance = initialBalance;
	    }

	    // Public getter and setter methods to access private data

	    public String getAccountNumber() {
	        return AcntNumber;
	    }

	    // Get and set account holder name
	    public String getAccountHolderName() {
	        return AcntHolder;
	    }

	    public void setAccountHolderName(String accountHolderName) {
	        this.AcntHolder = accountHolderName;
	    }

	    // Get balance (read-only, no direct setter)
	    public double getBalance() {
	        return balance;
	    }

	    // Deposit method (modifies private balance)
	    public void deposit(double amount) {
	        if (amount > 0) {
	            balance += amount;
	            System.out.println("\nDeposited amount ?" + amount);
	        } else {
	            System.out.println("Transaction failed!");
	        }
	    }

	    // Withdraw method (modifies private balance)
	    public void withdraw(double amount) {
	        if (amount > 0 && amount <= balance) {
	            balance -= amount;
	            System.out.println("Successfully withdrawn:?" + amount);
	        } else {
	            System.out.println("\nInsufficient funds!");
	        }
	    }

	    public static void main(String[] args) {
	        // Create a new bank account
	    	BankAccount1 account = new BankAccount1("00000001", "Arjun Kr Mandal", 999.00);

	        // Access account details using public methods
	        System.out.println("Account Holder: " + account.getAccountHolderName());
	        System.out.println("Account Number: " + account.getAccountNumber());
	        System.out.println("Current Balance: ?" + account.getBalance());

	        // Perform deposit and withdrawal
	        account.deposit(99.00);
	        System.out.println("Updated Balance: ?" + account.getBalance());

	        account.withdraw(9.00);
	        System.out.println("Updated Balance:  ?" + account.getBalance());

	        // Attempt invalid transactions
	        account.withdraw(9999.00); // Insufficient funds
	    }
	}

//output
Account Holder: Arjun Kr Mandal
Account Number: 00000001
Current Balance: ?999.0

Deposited amount ?99.0
Updated Balance: ?1098.0
Successfully withdrawn:?9.0
Updated Balance:  ?1089.0

Insufficient funds!        

Encapsulation in Java is typically achieved by declaring instance variables as private and providing controlled access to them through methods, such as getters and setters, for reading and modifying their values.

Remember, getter and setter methods are key to the encapsulation principle in object-oriented programming. They protect an object's internal state (e.g., the balance field) by preventing direct access from external code. Instead, interactions are managed through controlled methods.

In summary, the key benefits of encapsulation include:

  • Data hiding: Encapsulation prevents other developers from writing scripts or APIs that use your code.
  • Increased flexibility: You can change the internal implementation without affecting the external code.
  • Improved maintainability: You can keep fields private and use public methods to modify and view them.
  • Reusable programs : You can write programs that can be used multiple times.



Keep following https://www.dhirubhai.net/in/arjunkrm-testarchitect/ for such interesting topics.

要查看或添加评论,请登录

Arjun K.的更多文章

  • Little’s Law in Performance Testing

    Little’s Law in Performance Testing

    In 1954, John Little published a paper in which he described the queueing theory by a new law. Later, it is named…

  • Performance Metrics- Throughput, latency and response time!

    Performance Metrics- Throughput, latency and response time!

    Throughput Throughput serves as a crucial performance metric for assessing system efficiency, identifying bottlenecks…

  • Application Performance Improvement using CAST SQG formerly AIP.

    Application Performance Improvement using CAST SQG formerly AIP.

    ??What is CAST Structural Quality Gate (SQG) formerly AIP ? CAST SQG draws on CAST’s extensive experience in deep…

  • Performance Test-An Overview!

    Performance Test-An Overview!

    Performance testing is a type of software testing that focuses on how well an application performs under various…

  • Software Performance Test - An Overview!

    Software Performance Test - An Overview!

    Performance testing is a type of software testing that focuses on how well an application performs under various…

  • Compile-time & Runtime Errors in Java..

    Compile-time & Runtime Errors in Java..

    Compile-time A compile-time error in Java refers to an error that occurs during the compilation phase, when the Java…

  • Java for Everyone...Encapsulation.

    Java for Everyone...Encapsulation.

    Consider a real-life example of your bank account. Your account balance is private—you wouldn’t want anyone to directly…

  • Java Collection Framework in Selenium

    Java Collection Framework in Selenium

    In Selenium WebDriver, Java collections play a crucial role in managing and manipulating data such as lists of web…

  • Java for Everyone... Arrays

    Java for Everyone... Arrays

    An array is a container object that holds a fixed number of values of a single type. The length of an array is…

  • Java for Everyone... StringBuilder & StringBuffer

    Java for Everyone... StringBuilder & StringBuffer

    StringBuilder objects are like String objects, except that they can be modified. Internally, these objects are treated…

社区洞察

其他会员也浏览了