Encapsulation in Java Class Design
Encapsulation is one of the four Object-Oriented Programming concepts. The others are: Abstraction, Inheritance, Polymorphism.
Encapsulation refers to the practice of keeping data and the associated behaviour of the data as a single unit. This single unit in Java is called a Class.
Enforcing Encapsulation through Access modifiers
To enforce encapsulation in Java, fields are made private, while the methods required to expose the behaviours of these fields are also provided within the class itself. In other words, the class encapsulates its fields and methods together. That said, it is obvious that Java enforces encapsulation using access modifiers.
Java Access Modifers
There are four access modifiers supported in Java:
Access Modifier | Accessible by: |
---|---|
private | only by fields or methods within the same class |
protected | only by classes within the same package as well as subclasses of the class in question |
Default or package-protected (no access modifier specified) | only by classes within the same package |
public | any class, regardless of package boundary |
Additional points to note concerning Access Modifiers
- A class (or Interface) cannot be declared as private or protected
- Member methods or fields of an interface cannot be declared private or protected.