Java Access Modifiers¶
Introduction¶
Access modifiers in Java control where classes, attributes, methods, and constructors can be accessed.
Java provides four access levels:
publicprivateprotected- Default or package-private access
Access modifiers help to protect data, prevent unwanted changes, support encapsulation, and make code easier to maintain.
Access Modifier Syntax¶
An access modifier is written before an attribute or method.
Example:
Method example:
Public Access Modifier¶
The public modifier allows access from any class and any package.
HMIS-style action method:
Use public for:
- Getter methods
- Setter methods
- Controller action methods
- Service methods
- Facade methods
- Methods that must be accessed by other packages
Public attributes are usually not recommended:
Prefer a private attribute with public getters and setters:
private String patientCode;
public String getPatientCode() {
return patientCode;
}
public void setPatientCode(String patientCode) {
this.patientCode = patientCode;
}
Private Access Modifier¶
The private modifier allows access only inside the same class.
Private helper method:
private boolean isDateRangeValid() {
return fromDate != null
&& toDate != null
&& !fromDate.after(toDate);
}
Use private for:
- Attributes
- Internal helper methods
- Validation methods
- Query-building methods
- Sensitive information
Private attributes help to:
- Protect internal data
- Prevent direct modification
- Support validation through setters
- Reduce errors
- Support encapsulation
Protected Access Modifier¶
The protected modifier allows access:
- Inside the same class
- Inside the same package
- Inside child classes
HMIS-style example:
Facade example:
@Stateless
public class PatientInvestigationFacade
extends AbstractFacade<PatientInvestigation> {
@PersistenceContext(unitName = "hmisPU")
private EntityManager entityManager;
@Override
protected EntityManager getEntityManager() {
return entityManager;
}
}
Use protected when inheritance requires access to a method.
Prefer private attributes with protected methods:
private EntityManager entityManager;
protected EntityManager getEntityManager() {
return entityManager;
}
Default Access Modifier¶
When no access modifier is written, Java uses default access.
Default access is also called:
- Package-private access
- Package access
- No-modifier access
Example:
Method example:
A default member can only be accessed by classes in the same package.
HMIS-style example:
package com.divudi.bean.lab;
class LabReportHelper {
void prepareData() {
// Internal package logic
}
}
Access Modifier Comparison¶
| Modifier | Same class | Same package | Child class in another package | Other packages |
|---|---|---|---|---|
private |
Yes | No | No | No |
| Default | Yes | Yes | No | No |
protected |
Yes | Yes | Yes | No |
public |
Yes | Yes | Yes | Yes |
Access Modifiers for Attributes¶
Attributes should normally be private.
Recommended:
private String patientCode;
private Date createdAt;
private Department department;
private boolean retired;
Avoid:
Use public getters and setters:
public String getPatientCode() {
return patientCode;
}
public void setPatientCode(String patientCode) {
this.patientCode = patientCode;
}
Access Modifiers for Methods¶
Public method¶
Can be called by other classes or XHTML pages.
Private method¶
Can only be called inside the same class.
Protected method¶
Can be called by child classes and classes in the same package.
Default method¶
Can be called only from the same package.
Access Modifiers for Classes¶
A top-level Java class can normally use:
public- Default access
Public class:
Default-access class:
A top-level class cannot be declared private or protected.
Inner classes may use private, protected, or public.
Encapsulation with Access Modifiers¶
Encapsulation means keeping attributes private and accessing them through methods.
public class BillData {
private double total;
private double discount;
public double getTotal() {
return total;
}
public void setTotal(double total) {
if (total < 0) {
throw new IllegalArgumentException(
"Total cannot be negative"
);
}
this.total = total;
}
public double getDiscount() {
return discount;
}
public void setDiscount(double discount) {
if (discount < 0) {
throw new IllegalArgumentException(
"Discount cannot be negative"
);
}
this.discount = discount;
}
public double calculateNetTotal() {
return total - discount;
}
}
In this example:
totalanddiscountare private.- Getters provide read access.
- Setters provide controlled write access.
- Validation prevents invalid values.
calculateNetTotal()is public behaviour.
HMIS-Style Example¶
public class InvestigationReportData {
private Date fromDate;
private Date toDate;
private Department laboratory;
private Investigation investigation;
private List<PatientInvestigation> results =
new ArrayList<>();
public Date getFromDate() {
return fromDate;
}
public void setFromDate(Date fromDate) {
this.fromDate = fromDate;
}
public Date getToDate() {
return toDate;
}
public void setToDate(Date toDate) {
this.toDate = toDate;
}
public Department getLaboratory() {
return laboratory;
}
public void setLaboratory(Department laboratory) {
this.laboratory = laboratory;
}
public Investigation getInvestigation() {
return investigation;
}
public void setInvestigation(
Investigation investigation) {
this.investigation = investigation;
}
public List<PatientInvestigation> getResults() {
return results;
}
public void process() {
results.clear();
if (!isDateRangeValid()) {
return;
}
loadResults();
}
private boolean isDateRangeValid() {
return fromDate != null
&& toDate != null
&& !fromDate.after(toDate);
}
private void loadResults() {
// Load report results
}
}
Access modifiers used¶
| Member | Modifier | Reason |
|---|---|---|
| Attributes | private |
Protect internal data |
| Getters | public |
Allow controlled reading |
| Setters | public |
Allow controlled updating |
process() |
public |
Called from another component or XHTML |
isDateRangeValid() |
private |
Internal validation |
loadResults() |
private |
Internal processing |
Sensitive Data and Access Modifiers¶
HMIS contains sensitive patient and healthcare information.
private String patientName;
private String nationalIdentityCardNumber;
private String diagnosis;
private String investigationResult;
private String prescriptionDetails;
Sensitive attributes should be private.
Avoid:
Prefer:
Only provide a public getter when the information must be accessed:
Access modifiers alone do not provide full security. The application must also use authentication, authorization, role-based access, audit logging, and secure database access.
Common Mistakes¶
Public attributes¶
Avoid:
Use:
Private method needed by XHTML¶
Incorrect:
Correct:
Public internal helper method¶
Avoid:
when only the same class uses it.
Prefer:
Protected attributes without a reason¶
Avoid:
Prefer:
Using default access accidentally¶
If the attribute should be private, write:
Best Practices¶
- Keep attributes private.
- Use public getters and setters only when required.
- Keep internal helper methods private.
- Use protected methods only for inheritance.
- Use default access only for package-level design.
- Avoid public mutable attributes.
- Do not expose sensitive patient information unnecessarily.
- Use the smallest access level required.
- Do not make everything public.
- Review access levels when refactoring code.
Summary¶
Java has four access levels:
From most restricted to least restricted:
Recommended HMIS usage:
private String patientCode;
public String getPatientCode() {
return patientCode;
}
public void setPatientCode(String patientCode) {
this.patientCode = patientCode;
}
private boolean validatePatientCode() {
return patientCode != null
&& !patientCode.trim().isEmpty();
}
Important rules:
- Attributes should normally be private.
- Public methods provide controlled access.
- Private methods contain internal logic.
- Protected methods support inheritance.
- Default access limits members to the same package.
- Use the smallest access level necessary.