Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Encapsulation
2.1.
Example
2.2.
Output
2.3.
Explanation
3.
Advantages of Encapsulation
4.
FAQs
5.
Key Takeaways
Last Updated: Mar 27, 2024

Encapsulation in Java

Author Saksham Gupta
0 upvote
gp-icon
Data structures & algorithms (Beginner to Intermediate)
Free guided path
13 chapters
99+ problems
gp-badge
Earn badges and level up

Introduction

When it comes to technical interviews, interviewers frequently focus on OOPS. The questions are mostly theoretical, and one's understanding of oops should be on point. On the other hand, you do not need to be concerned about any of it. Ninjas are here to help, and today we'll go over one of the most often asked topics about this subject., i.e., Encapsulation in Java.

Encapsulation

The bundling up of data into a single unit is referred to as encapsulation. It's the glue that holds code and the data it manipulates together. Encapsulation can also be thought of as a protective shield that prevents data from being accessible by code outside of the shield.

Source: source

Encapsulation means that a class's variables or data are hidden from other classes and can only be accessed through member functions of the class in which it is stated.

The data hiding concept is achieved by making a class's members or methods private, and the class is presented to the end-user or the world without disclosing any information behind implementation using the abstraction concept, hence it's also known as a combination of data-hiding and abstraction.

Declare all variables in the class as private and write public methods in the class to set and get the values of variables to accomplish encapsulation. Also see,  Swap Function in Java

Now let's see an example of encapsulation.

Example

class Encapsulation{
   
    /* Variables */
    private int rating;
    private String coder;
    private int age;

    / *Getter and Setter methods */
    public int getRating(){
        return rating;
    }

    public String getCoder(){
        return coder;
    }

    public int getAge(){
        return age;
    }

    public void setAge(int newValue){
        age = newValue;
    }

    public void setCoder(String newValue){
        coder = newValue;
    }

    public void setRating(int newValue){
        rating = newValue;
    }
}
class EncapsulationDemo{
    public static void main(String args[]){
       
        /* Creating a new object*/
         Encapsulation codingNinja = new Encapsulation();
         codingNinja.setCoder("Ankush");
         codingNinja.setAge(39);
         codingNinja.setRating(1900);

         System.out.println("Coder: " + codingNinja.getCoder());
         System.out.println("Age: " + codingNinja.getAge());
         System.out.println("Rating: " + codingNinja.getRating());
    }
}

Output

Coder: Ankush
Age: 39
Rating: 1900

Explanation

In the above example, we can see that the three data members, namely 'coder,' 'age,' and rating, are made private, which means they can be accessed directly. Then how can we access them?

By using member functions of the same class(Getters and Setters).

Thus, we have used the encapsulation technique to hide these variables.

Now, let's discuss the advantages of encapsulation.

You can also read about the Multiple Inheritance in Java, Duck Number in Java.

Must Read Type Conversion in Java

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Advantages of Encapsulation

Data Hiding: The user will be unaware of the class's internal implementation. The user will be unable to observe how the class keeps variables values. Only the user will be aware that the values are supplied to a setter method and that variables are set to that value.

Increased Flexibility: Depending on our needs, we can make the class's variables read-only or write-only. If we want the variables to be read-only, we must remove the setter methods like set_FunctionNmae(); if we want the variables to be write-only, we must remove the get methods like get_FunctionName().

Reusability: Encapsulation also promotes reusability and makes it simple to adapt to changing requirements.

Testing code is easy: Unit testing is simple with encapsulated code.

You can also find the output of this java compiler code here.

Know about Single Inheritance in Java in detail.

FAQs

  1. Why is Java a platform-independent language?
    Because it does not rely on a platform, Java is platform-independent. Java will now be a platform-agnostic language. Programs are compiled into byte code in Java, which is platform-agnostic. The Java Virtual System is required to run byte code on any machine.
     
  2. Why is Java not a purely object-oriented language?
    Because it supports primitive data types such as int, byte, long, short, and so on, Java is not a fully object-oriented language. As a result, data types such as int, float, double, and others are not object-oriented. As a result, Java is not entirely object-oriented.
     
  3. What is the use of the Java util package?
    It contains the classes needed to make an applet that can communicate with its applet context. It includes all of the classes needed to create user interfaces as well as paint graphics and pictures.
     
  4. Why do we use import Java util.*?
    It means importing all the classes and interfaces within java.util package and making them available within the current class or interface. This is shorthand wild card annotation for importing all classes within a particular package.
     
  5. Is there any other Data Structures and Algorithms content in Coding Ninjas Studio?
    It entails bringing all of the classes and interfaces in the java.util package into the current class or interface. This is a shortcut wildcard annotation for importing all classes included within a specific package.

Key Takeaways

In this article, we have extensively discussed Encapsulation in JavaWe hope that this blog has helped you enhance your knowledge of Encapsulation in Java, and if you would like to learn more, check out our articles on Library. Do upvote our blog to help other ninjas grow. 

Explore more related article: 

Happy Coding!”

Previous article
Super Keyword in Java
Next article
Difference between Abstraction and Encapsulation
Guided path
Free
gridgp-icon
Data structures & algorithms (Beginner to Intermediate)
13 chapters
109+ Problems
gp-badge
Earn badges and level up
Live masterclass