wellnwill Marathahalli Bangalore

Encapsulation in java


The process of Binding of data member and member functions into a single unit is known as encapsulation. Every java class is an example of encapsulation.

We can achieve more encapsulation by making field’s private and providing an access to private field through public methods.

We can create fully encapsulated class by making data members as private, encapsulation is also referred as data hiding.

Public method which is used to assign value to the private data member is known as setter method. Public method which is used to access the value of private data member is known as getter method.


class Bank
{
 private double amount;
 private String name;
 public double getAmount()
 {
  return amount;
 }
 public void setAmount(double d)
 { 
    if(d > 100)
    {
      amount=d;
    }
 }
 public String getName()
 {
   return name;
 }
  public void setName(String s)
 {
  name=s;
 }
}

class Test
{
public static void main(String args[]){
 Bank b1=new Bank();
 b1.setAmount(100000);
 b1.setName("Dheeraj");
 System.out.println("amount :"+b1.getAmount());
 System.out.println("account holder :"+b1.getName());
 }
}
Output- amount: 100000.0
         Account holder : Dheeraj


Advantage of Encapsulation:


The main advantage of encapsulation is to achieve security. Full control on the data which is going to store.


Singleton class

  • A Singleton class is one which allows us to create only one object throughout the application execution.
  • If many people have same requirement then we can create only one object and reuse the same object for every similar requirement.
  • The advantage of this approach is to improve the performance and make better use of memory.

How to create singleton class

  • We have to use private constructor so that users cannot create object directly while calling constructor outside the class and private static variable.
  • Create a public static method which will create an object and return object reference if the object is not already created.
  • If object is already created then return the same object reference.

class DBCon
{
 private static DBCon con=null;
 private DBCon()
 {
 }
 public static DBCon getObject()
 {
  if(con==null)
  {
   con=new DBCon();
  }
  return con;
 }
}

class Test
{
public static void main(String args[])
{
 DBCon con1=DBCon.getObject();//
 DBCon con2=DBCon.getObject();
 DBCon con3=DBCon.getObject();
 System.out.println(con1);
 System.out.println(con2);
 System.out.println(con3);
 }
}
Output-  DBCon@1db23
         DBCon@1db23
         DBCon@1db23

Footer with Map