Home Encapsulation in java

Encapsulation in java

Data Protection or Data Wrapup called as Encapulation.Encapsulation implies that the non-essential data hidden from the
user and an access is provided to its essential data.

For example, when you plug in the washing machine and switch it on, the washing machine starts functioning. An end-user need not know
the working principle of a washing machine to convert electricity into suction power. The switch of the washing machine encapsulates the complex process of conversion of electricity into suction power. The complexity of an data is hidden as a result of encapsulation.

 How to create a fully  encapsulate class

1.create with private attributes

2.create no arg constructor & full arg constructor

3.Create setters  and getters

First create the  class Customer. i have explained below.how to create private attributes,create no arg constructor & full arg constructor,Create setters  and getters

Customer.java

public class Customer {

    //Make all Variables as Private
    private String name;
    private String address;
    private String phone;

    public Customer()  //default constructor
    {
    }

    public Customer(String name, String address, String phone) //full arg constructor
    {
        this.name = name;
        this.address = address;
        this.phone = phone;
    }
        //getters
    public String getName() {

        return name;
    }
    //setters
    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {

        this.address = address;
    }

    public String getPhone() {

        return phone;
    }

    public void setPhone(String phone) {

        this.phone = phone;
    }
}

Main.java

public class Main {

    public static void main(String args[]) {

        Customer customer = new Customer("kumar", "india", "21312312"); // set all the data full arg constructor.

        System.out.println(customer.getName());

        System.out.println(customer.getAddress());
        System.out.println(customer.getPhone());

     // Imagin if the have only one data use like this way
        customer.setName("Ravi");

    }
}

 

Comments are closed.