Encapsulation in Java With Examples

Encapsulation is the process of wrapping all the code and data and making a single unit from them. In it, the variable of a class will only be accessible through the methods of their current class and are hidden from other classes. Encapsulation is also known as data-hiding as it hides the data in a class from other classes. It works as a kind of a shield to protect data from being accessed by the code outside.

It is achieved by declaring all the variables in the class as private and writing public methods to find out the values of the variables. Java bean is an example of such encapsulation as all data members are private here.

Advantages of encapsulation in Java

1. Data hiding:

Encapsulation is achieved by declaring all the variables in a class as private. This helps the user to hide the code and only make the essential parts visible.

2. Easy to test the code:

It is easier to perform unit testing to test the codes that have been encapsulated.

3. Flexibility is increased:

Encapsulation increases the flexibility to make the class read-only or write-only.

4. Reusability:

Encapsulation makes the code easily reusable and new features can be easily added to the program.

Here is a simple example:


package com.corejava.encapsulation;

public class FirstClass {

	private int age;

	public void setAge(int number) {
		age = number;

	public int GetAge() {
		return age;


package com.cubic.Encapsulation;

public class MainClass {

	public static void main(String[] args) {

		FirstClass fc = new FirstClass();


Check also: Polymorphism in Java [Method Overloading & Overriding]

Access modifiers in Java

The keywords that are added to the definitions in order to change their meaning are called modifiers. In Java, there are two types of modifiers that are used. They are Access modifiers and Non-access modifiers.

Access modifiers are those modifiers that restrict the accessibility of class, variable, constructor, method, and data member. There are four types of access modifiers that are present in Java. They are private, default, protected, and public.

Besides the modifiers restricting the accessibility of the classes and variables, there are various other modifiers that perform various other functions in Java. Such modifiers are called non-access modifiers. Static modifier, final modifier, abstract modifier, synchronized modifier, and volatile modifier are some of the types of non-access modifiers.

Access modifiers in Java

Now let us deal with the types of access modifiers.

1. Private access modifier

Private access modifier is visible only to the class in which they are declared. Other class cannot access the members or methods that are declared as private. Only methods and data members can be declared private using the private keyword, not the classes and interfaces.

public class PublicClass {
    private void firstMethod() {
        // ...
  private void secondMethod() {

When a class constructor is declared as private, a user cannot create an instance of that class from outside the class.

2. Protected access modifier

The data members and methods that are specified with protected access modifier are visible to the same package and all the subclasses in a different package. Only methods and data members can be declared protected using the protected keyword, not the classes.

The data members and methods that are specified with a protected access modifier are only accessible outside the package only through inheritance.

public class PublicClass {
     protected void methodProtected() {

3. Public access modifier

The classes, methods, and data members that are specified with public access modifiers are visible everywhere. It has the widest scope among all the access modifiers as there is no restriction on the accessibility of the classes and data members that are declared public using the public keyword.

public class PublicClass {
    static void method() {
        // ...

4. Default access modifier

Default access modifiers are declared by default in the situation where no access modifier is declared to a class, data member, and method. The classes, data members, and methods that are specified with a default access modifier are only accessible within the same package.

public class PublicClass {
    static void defaultMethod() {

Java access modifiers with method overriding

The methods that are overridden must be specified with public access modifiers to make it less restrictive. If the methods are declared as private or default then it becomes more restrictive and throws a compile-time error.

Check also: OOPs Concepts in Java – Four Main Concepts

Java Package

A package is a container of a group of related classes, sub packages, enumerations, annotations, and interfaces. It is used for access protection as some of the classes in a package are exposed and other are kept hidden. It provides namespace management so it prevents naming conflicts with names in different packages.

Packages are used to easily use and search classes, annotations, enumeration, and interfaces. Packages can be further classified into two types, built0in packages, and user-defined packages. Built-in packages are the packages already present in the Java such as java.lang, java.io, java.net, java.swing, java.util, and java.sql.

User-defined packages are the packages that are defined by the users themselves to bundle a group of classes for their convenience. Creating user-defined packages helps the user to easily locate and use the classes, interfaces, annotation, and enumerations. Packages are created using the package keyword.

In this chapter, the process of how user-defined packages are created and used will be dealt with.

Benefits of Java package

The main advantages of using packages in Java are:

  1. Packages help to easily maintain, locate, and use the classes, interfaces, annotations, and enumerations as the related classes and interfaces are categorized together.
  2. In a package, some classes are easily accessible and others are protected from the user. So it provides controlled access.
  3. Packages remove naming conflicts by creating a new namespace.

How to access package from another package?

A package can be accessed from outside the package in three ways. They are:

    1. Import package.*
    2. Import package.classname
    3. Fully qualified name

1. Using packagename.*

The classes and interfaces inside a package can be access from outside the package by using package.* But the subpackages of the package will not be accessible by using this method. The classes and interfaces of another package can be made accessible to the current page by using the import keyword.

2. Using packagename.classname

By using packagename.classname to import a package from outside the package, only the declared class will be accessible.

3. Using a fully qualified name

The fully qualified name is used to access classes and interface from outside the package when there are two classes with the same name in different packages. The fully qualified name of the class has to be used every single time to access it and only the declared class will be accessible. However, there is no need to import the package using this method.

Subpackage in Java

Subpackages are those packages that are inside another package. Subpackages are taken as a different package from the package that they are so that the classes are protected. The classes or interface of a subpackage lack the access privileges and they have to be imported explicitly.

Ways to load the class files or jar files

There are two methods used for loading the class files in Java. They are:

1. Temporary way:

  • Through the classpath switch.
  • Through setting the classpath in the command prompt.

2. Permanent way:

  • Through setting the classpath in the environment variables.
  • By first creating the jar file first that contains all the class files. And then copy the created jar file in the jre/lib/ext folder.

How to put two public classes in a package?

Two public classes are put in a package by creating two java source files that contain one public class but naming them differently.

Leave a Reply

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