Encapsulation in Java

In this article we will discuss one of the main object oriented concepts in Java, encapsulation.

Encapsulation

Basically encapsulation is the process of binding related functionalities (methods) and data (variables) into a protective wrapper (class) with required access modifiers (public, private, default, protected) so that the codes can be saved from unauthorised access the by outer world and can be made easy to maintain.

It can also be defined as the process of wrapping the code and data into a single unit.

Encapsulation can be completely achieved by making the class private and access them outside the class by using getters and setters. If we make the class public then a lesser degree of encapsulation is provided.

By providing getters and setters we can make the class read-only and write-only as well as we can have the control over the data.

Now let's use an example to understand the concept of encapsulation.

Example of Encapsulation in Java

This example contains two Java files, one named Vehicle.java and the other one is Main.java with the main class Details.

Vehicle.java

public class Vehicle

{

    private String category;

    private String brand;

    private int price;

    private String colour;

 

    public String getCategory()

    {

        return category;

    }

    public void setCategory(String category)

    {

        this.category = category;

    }

    public String getBrand()

    {

        return brand;

    }

    public void setBrand(String brand)

    {

        this.brand = brand;

    }

    public int getPrice()

    {

        return price;

    }

    public void setPrice(int price)

    {

        this.price = price;

    }

    public String getColour()

    {

        return colour;

    }

    public void setColour(String colour)

    {

        this.colour = colour;

    }

} 

Main.java

class Details

{

    public static void main(String args[])

    {

        Vehicle v=new Vehicle();

        v.setCategory("four wheeler");

        v.setBrand("mercedes");

        v.setPrice(1000000);

        v.setColour("grey");

        System.out.println("The details of the vehicle:");

        System.out.println("The type of vehicle:" +v.getCategory());

        System.out.println("The brand name of vehicle:" +v.getBrand());

        System.out.println("The price of the vehicle:" +v.getPrice() +"lakhs");

        System.out.println("The colour of the vehicle:" +v.getColour());

    }

}

Output of the example:

Output 

Up Next
    Ebook Download
    View all
    Learn
    View all