Java:封装

Q. What is the difference between abstraction and encapsulation?

  • Abstraction solves the problem at design level while Encapsulation solves it implementation level.
  • In Java, Abstraction is supported using interface and abstract class while Encapsulation is supported using access modifiers e.g. public, private and protected.
  • Abstraction is about hiding unwanted details while giving out most essential details, while Encapsulation means hiding the code and data into a single unit e.g. class or method to protect inner working of an object from outside world.
AbstractionEncapsulation
Abstraction is a process of hiding the implementation details and showing only functionality to the user. Encapsulation is a process of wrapping code and data together into a single unit
Abstraction lets you focus on what the object does instead of how it does it. Encapsulation provides you the control over the data and keeping it safe from outside misuse.
Abstraction solves the problem in the Design Level. Encapsulation solves the problem in the Implementation Level.
Abstraction is implemented by using Interfaces and Abstract Classes. Encapsulation is implemented by using Access Modifiers (private, default, protected, public)
Abstraction means hiding implementation complexities by using interfaces and abstract class. Encapsulation means hiding data by using setters and getters.

Q. How Encapsulation concept implemented in JAVA?

Encapsulation in Java is a mechanism of wrapping the data (variables) and code acting on the data (methods) together as a single unit. In encapsulation, the variables of a class will be hidden from other classes, and can be accessed only through the methods of their current class. Therefore, it is also known as data hiding.

To achieve encapsulation in Java −

  • Declare the variables of a class as private.
  • Provide public setter and getter methods to modify and view the variables values.

Example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class EncapClass {
private String name;

public String getName() {
return name;
}
public void setName(String newName) {
name = newName;
}
}

public class MainClass {

public static void main(String args[]) {
EncapClass obj = new EncapClass();
obj.setName("Pradeep Kumar");
System.out.print("Name : " + obj.getName());
}
}