• Encapsulation in Java | Java Tutorial

    Encapsulation is a mechanism of binding code and data together in a single unit. Let’s take an example of Capsule. Different powdered or liquid medicines are encapsulated inside a capsule. Likewise in encapsulation, all the methods and variables are wrapped together in a single class.

    Encapsulation In Java

    We will see detailed explanation with some example programs about Encapsulation in the post related to Encapsulation.

    Let’s see how can we implement encapsulation. Set the instance variables private so that these private variables cannot be accessed directly by other classes. Set getter and setter methods of the class as public so that we can set and get the values of the fields.

    Let’s see a sample program.

     

    Output:

    In the above example, you can find all the data member (variables) are declared as private. If the data member is private it means it can only be accessed within the same class. No other class can access these private variables of other class. To access these private variables from other classes, we used public getter and setter methods such as getAge(), getName(), setAge(), setName(). So, the data can be accessed by public methods when we can set the variables private and hide their implementation from other classes. This way we call encapsulation as data hiding.

    Must Read: Java Tutorial

    Sharing is caring.

    Share on facebook
    Facebook
    Share on twitter
    Twitter
    Share on linkedin
    LinkedIn

    Like This Post?

    We have a lot more where that came from?

    We only send really good stuff occasionally, promise.

    Rajkumar SM

    2 thoughts on “Encapsulation in Java | Java Tutorial”

    Leave a Comment

    Your email address will not be published. Required fields are marked *

    Scroll to Top
    API Testing eBook

    DOWNLOAD FOR FREE