-
Notifications
You must be signed in to change notification settings - Fork 137
java theories access modifiers
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.
An access modifier is written before an attribute or method.
accessModifier dataType attributeName;Example:
private String patientName;Method example:
public String getPatientName() {
return patientName;
}The public modifier allows access from any class and any package.
public String getPatientCode() {
return patientCode;
}HMIS-style action method:
public void processReport() {
// Generate report
}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:
public String patientCode;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;
}The private modifier allows access only inside the same class.
private String patientName;
private Department department;
private Investigation investigation;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
The protected modifier allows access:
- Inside the same class
- Inside the same package
- Inside child classes
HMIS-style example:
@Override
protected EntityManager getEntityManager() {
return entityManager;
}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;
}When no access modifier is written, Java uses default access.
Default access is also called:
- Package-private access
- Package access
- No-modifier access
Example:
String internalCode;Method example:
void clearTemporaryData() {
}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
}
}| 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 |
Attributes should normally be private.
Recommended:
private String patientCode;
private Date createdAt;
private Department department;
private boolean retired;Avoid:
public String patientCode;
public Date createdAt;Use public getters and setters:
public String getPatientCode() {
return patientCode;
}
public void setPatientCode(String patientCode) {
this.patientCode = patientCode;
}public void process() {
}Can be called by other classes or XHTML pages.
private boolean validateFilters() {
return fromDate != null && toDate != null;
}Can only be called inside the same class.
protected EntityManager getEntityManager() {
return entityManager;
}Can be called by child classes and classes in the same package.
void resetInternalState() {
}Can be called only from the same package.
A top-level Java class can normally use:
public- Default access
Public class:
public class InvestigationReport {
}Default-access class:
class InvestigationReportHelper {
}A top-level class cannot be declared private or protected.
Inner classes may use private, protected, or public.
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.
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
}
}| 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 |
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:
public String diagnosis;Prefer:
private String diagnosis;Only provide a public getter when the information must be accessed:
public String getDiagnosis() {
return diagnosis;
}Access modifiers alone do not provide full security. The application must also use authentication, authorization, role-based access, audit logging, and secure database access.
Avoid:
public String patientName;Use:
private String patientName;Incorrect:
private void process() {
}Correct:
public void process() {
}Avoid:
public boolean isDateRangeValid() {
}when only the same class uses it.
Prefer:
private boolean isDateRangeValid() {
}Avoid:
protected Department department;Prefer:
private Department department;String patientCode;If the attribute should be private, write:
private String patientCode;- 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.
Java has four access levels:
private
default
protected
public
From most restricted to least restricted:
private → default → protected → public
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.