❌

Normal view

There are new articles available, click to refresh the page.
Before yesterdayMain stream

Encapsulation

By: Prasanth
13 June 2025 at 06:53

What is Encapsulation ?

  • Encapsulation is the process of wrapping data(variables) and code (methods) together as a single unit . It hides the internal state of object from outside access, that mean the variable of a class will be hidden from other classes, and can be accessed only through method of current class. Encapsulation used to achieve data hiding ,not itself data hiding.

Why Use Encapsulation

  • protects Data : keep important Fields are private (data-variable) safe from direct access.
  • Hides Details : show only necessary thins to the user
  • Controls Access:- gives control over who can read or change the data. that mean you can lock you data using private and you give a key (get/set method) to trusted one,only change authorized class or user.
  • Easy to change: you can change the code inside without affecting other code and also you can use another project Encapsulated project

Achieving Encapsulation in java:-

Declare the variables of a class as private.
provide public setters(write-only) and getters(read-only) methods to modify and view the variables values.

Benefits of Encapsulation:-
The fields(global variable ) of class can be made read-only (or) write-only. class can have total control over what is stored in the fields.

Example:-

package encapsulation;

public class BankAccount {

    // private variable - hidden from outside
    private  String  accountHolderName;
    private int accountNumber;
    private double balance;



    // constructor
    BankAccount(String name ,int accNumber, double initialBalance)

    {
        this.accountHolderName=name;
        this.accountNumber=accNumber;
        if (initialBalance >=0)
        {
        this.balance=initialBalance;

        }
        else
        {
            System.out.println("Invalid blance! setto 0 by default. ");
            this.balance=0;
        }
    }

    public String getAccountHolderName()
    {
        return accountHolderName;
    }

    public void setAccountHolderName(String name)
    {
        if (name != null && !name.isEmpty())
        {
    this.accountHolderName= name;
        }else
        {
            System.out.println("Invalid name!");

        }
    }
    // Get balance (no direct access to variable)
    public double getBalance()
    {

        return balance;
    }
    // withdraw method with check
    public void deposit(double amount)
    {
        if (amount > 0 )
        {
            balance += amount;
            System.out.println("Deposited: "+ amount);
        }
        else {
            System.out.println("Invalid deposite amount!   ");

        }
    }

    // deposit method with validation
    public void withdraw (double amount)
    {
    if (amount > 0 &&amount <= balance)
    {

        balance -= amount;
        System.out.println(" Withdrawn:"+ amount);
    }
    else
    {
        System.out.println("Invalid funds");
    }
    }

    //Display details (read-only)

    public void displayAccountInfo()
    {
        System.out.println("Account Holder: "+ accountHolderName);
        System.out.println("Account Number: "+ accountNumber );
        System.out.println("Current Balance: "+ balance);


    }

}



package encapsulation;

public class Bank_Main {

    public static void main(String[] args) {


        BankAccount account = new BankAccount("Prasanth",1001,5000);

    account.displayAccountInfo();
    account.deposit(1500);
    account.displayAccountInfo();



    //Trying to withdraw
    account.withdraw(1500);
    account.displayAccountInfo();



    //trying to withdraw
    account.withdraw(2000);
    account.displayAccountInfo();

    // Trying to set a bad name
    account.setAccountHolderName("");
    account.setAccountHolderName("sam");
    System.out.println("updated name:" +account.getAccountHolderName());


    //trying invalid operations
    account.deposit(-500);
    account.withdraw(10000); //more than balance

    }



}

Encapsulation Read-only class

Example:2

package encapsulation;

// Creating Write-Only Class
public class FruitShop {

    private String fruitname;
    private int fruitprice;

    public  void setName(String name)
    {
        this.fruitname=name;

    }

    public void  setfruitPrice(int price)
    {
        this.fruitprice=price;
    }
}


package encapsulation;

// Creating Write-Only Class
public class FruitShop {

    private String fruitname;
    private int fruitprice;

    public  void setName(String name)
    {
        this.fruitname=name;

    }

    public void  setfruitPrice(int price)
    {
        this.fruitprice=price;
    }
}


Read and write:-

package encapsulation;

public class TechwaveEmployee {

    private String emp_name;
    private String  emp_id;
    private double net_salary;

    TechwaveEmployee(String emp_name,String emp_id ,double net_salary)
    {
        this.emp_name =emp_name;
        this.emp_id = emp_id;
        this.net_salary = net_salary;
    }

    public String getEmp_name() {
        return emp_name;
    }

    public void setEmp_name(String emp_name) {
        this.emp_name = emp_name;
    }

    public String getEmp_id() {
        return emp_id;
    }

    public void setEmp_id(String emp_id) {
        this.emp_id = emp_id;
    }

    public double getNet_salary() {
        return net_salary;
    }

    public void setNet_salary(double net_salary) {
        this.net_salary = net_salary;
    }
}




package encapsulation;

public class TechWaveHr {

    public static void main(String[] args) {

        // first object - setting values using constructor
        TechwaveEmployee person1 = new TechwaveEmployee("Prasanth","Empl001",15000.00);

        TechWaveHr person2 =  new TechWaveHr();

        // printing data
        System.out.println("Employee (Initial values):");
        System.out.println(person1.getEmp_id()+ " , "+ person1.getEmp_name()+" ," + person1.getNet_salary());

        // updating values setter methods
        person1.setEmp_id("Empl002");
        person1.setEmp_name("Vishal");
        person1.setNet_salary(50000.00);


        //printing data

        // printing data
                System.out.println("Employee (Updated values):");
                System.out.println(person1.getEmp_id()+ " , "+ person1.getEmp_name()+" ," + person1.getNet_salary());

    }

}



Let’s Build a Bank Account Simulation

26 May 2025 at 14:50

Problem Statement

🧩 Overview

Build a bank system to create and manage user accounts, simulate deposits, withdrawals, interest accrual, and overdraft penalties.

🎯 Goals

  • Support multiple account types with different rules
  • Simulate real-world banking logic like minimum balance and interest
  • Track user actions securely

πŸ— Suggested Classes

  • BankAccount: account_number, owner, balance, deposit(), withdraw()
  • SavingsAccount(BankAccount): interest_rate, apply_interest()
  • CheckingAccount(BankAccount): minimum_balance, penalty
  • User: name, password, accounts[]

πŸ“¦ Features

  • Create new accounts (checking/savings)
  • Deposit money to account
  • Withdraw money (with rules):
    • Checking: maintain minimum balance or pay penalty
    • Savings: limit to 3 withdrawals/month
  • Apply interest monthly for savings
  • Show account summary

πŸ”§ OOP Concepts

  • Inheritance: SavingsAccount and CheckingAccount from BankAccount
  • Encapsulation: Balance, account actions hidden inside methods
  • Polymorphism: Overridden withdraw() method in each subclass

πŸ”Œ Optional Extensions

  • Password protection (simple CLI input masking)
  • Transaction history with timestamp
  • Monthly bank statement generation

❌
❌