Applying access modifiers
One of the cornerstones of OOP is the principle of encapsulation (data abstraction). Encapsulation can be achieved using access modifiers. Before we discuss encapsulation, we must understand the access modifiers themselves.
Access modifiers determine where a class, field, or method is visible and therefore available for use. The level you are annotating at, determines the available access modifiers:
- Top level: Classes, enums, records and interfaces –
public
or package-private (no keyword) - Member level: The access modifiers are, in order from most restrictive to least restrictive,
private
, package-private,protected
, andpublic
Let’s discuss these in turn.
private
A member marked as private
is accessible within its own class only. In other words, the block scope of the class defines the boundary. When in a class (scope), you cannot access the private
members of another class, even if you have an object reference to...