Java Encapsulation

Data Encapsulation is a process of wrapping up the datamembers into a single unit. Which means binding of the datamembers and corresponding methods into a single unit.

Encapsulation = Data Hiding + abstraction

Data Hiding

Data Hiding is hiding internal data from outside users. The internal data should not go directly that is outside person/classes is not able to access internal data directly. It is achieved by using an access specifier- a private modifier.

Abstraction

Abstraction is a process of hiding internal implementation, which can achived with the help of abstract classes and interfaces



How Encapsulation is achieved in JAVA

  1. • Make all the data members private.
  2. • Create public setter and getter functions for each data member in such a way that the set function set the value of data member and get function get the value of data member.

Example of Encapsulation


    package com.example.domian;

    public class Customer {

        private long accountNumber;
        private String accountHolderName;
        private double balance;
        private int age;
        private String address;

        public long getAccountNumber() {
            return accountNumber;
        }

        public void setAccountNumber(long accountNumber) {
            this.accountNumber = accountNumber;
        }

        public String getAccountHolderName() {
            return accountHolderName;
        }

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

        public double getBalance() {
            return balance;
        }

        public void setBalance(double balance) {
            this.balance = balance;
        }

        public int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
        }

        public String getAddress() {
            return address;
        }

        public void setAddress(String address) {
            this.address = address;
        }

    }

Advantages

  1. • We can achieve the security
  2. • Enhancement will become very easy.
  3. • It improves the maintainability and modularity of application.
  4. • It provides flexibility to the user, to use system very easily.

Dis-Advantage

  1. • The main dis-advantage of encapsulation is, it increases the length of the code and slow down the system.