Encapsulation in Java

Encapsulation is the hiding of data and code from outside interference.
The data and code can only be accessed/modified by the class in which it is defined. This is achieved by declaring the variables as private and getters/setters as public.

Note: private and public are access specifiers about which we will talk a little later.

The getters and setters are methods used to get or modify the code and data.

Let’s see how our code looks without proper encapsulation.

class MyClass{
	public int age;
	public String name; 
}


public class WithoutEncapsulation {

	public static void main(String[] args) {
		MyClass obj=new MyClass();
		obj.age=40;//notice that we are able to modify variables that belong to MyClass from a 
                            //different class(WithoutEncapsulation) 
		obj.name="Java Guy";//notice that we are able to modify variables that belong to MyClass from 
                                     //a different class(WithoutEncapsulation) 
		System.out.println("name="+obj.name+" age="+obj.age);//notice that we are able to access 
                            //variables that belong to MyClass from a different class(WithoutEncapsulation) 

	}

}

Output:

name=Java Guy age=40

Now let’s see how our code looks without proper encapsulation.

class MyClass1{
	private int age;
	private String name;
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	} 

}

public class WithEncapsulation {

	public static void main(String[] args) {
		MyClass1 obj=new MyClass1();
		obj.age=40;//this will give error we are not able to modify variables that belong to MyClass from a different class(WithoutEncapsulation) 
		obj.name="Java Guy";//this will give error  we are not able to modify variables that belong to MyClass from a different class(WithoutEncapsulation) 
		System.out.println("name="+obj.name+" age="+obj.age);//this will give error we are not able to access variables that belong to MyClass from a different class(WithoutEncapsulation) 


	}

}

Output:

Exception in thread "main" java.lang.Error: Unresolved compilation problems: 
	The field MyClass1.age is not visible
	The field MyClass1.name is not visible
	The field MyClass1.name is not visible
	The field MyClass1.age is not visible

	at corejava.WithEncapsulation.main(WithEncapsulation.java:25)

We got an error because the variables age and name are private to the class MyClass1 and hence not visible to the class WithEncapsulation.

But notice that the getters and setters (getAge(),setAge(int age),getName(),setName(String name)) are methods of the same class as the variables age and name and hence can access them. Also since the getters and setters are public, we can access them from another class(i.e., WithEncapsulation).
Let’s see this in action.

class MyClass1{
	private int age;
	private String name;
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	} 

}

public class WithEncapsulation {

	public static void main(String[] args) {
		MyClass1 obj=new MyClass1();
		obj.setAge(40);//using setter to modify variable age
		obj.setName("Java Guy");//using setter to modify variable name
		System.out.println("name="+obj.getName()+" age="+obj.getAge());//using getters to access variables age and name


	}

}

Output:

name=Java Guy age=40

Access Specifiers in Java

There are 4 access specifiers in Java

  • public
  • private
  • protected
  • default

Public Access Specifier: If an identifier is declared as public, it will be accessible to all classes within the package in which it is declared as well as other packages.

Private Access Specifier: If an identifier is declared private, it can be accessed only within the class in which it has been declared.

Protected Access Specifier: If an identifier is declared as protected, it can be accessed by all the classes in the same package as well as all the classes that are derived from the current class in other packages.

Protected Access Specifier: If no access specifier is mentioned for the identifier then it is the default access specifier. Such identifiers are accessible by all classes in the same package but not by classes of the other packages.

Wrapping it up…

In this blog, we have discussed Encapsulation in Java which is one of the most important principles of Object Oriented Programming. But as we know Java is vast and its vastness can sometimes be scary to new learners.
But not to worry as I’ll be covering most of the important topics that you can face while developing a website.
If your goal is to get a professional certification for Java you can refer to this course by Edureka and for an overall understanding of Java web development, you can refer to this course by Udacity.

Related topics