# Java Access Modifiers ## Introduction Access modifiers in Java control where classes, attributes, methods, and constructors can be accessed. Java provides four access levels: 1. `public` 2. `private` 3. `protected` 4. 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. ```java accessModifier dataType attributeName; ``` Example: ```java private String patientName; ``` Method example: ```java public String getPatientName() { return patientName; } ``` --- ## Public Access Modifier The `public` modifier allows access from any class and any package. ```java public String getPatientCode() { return patientCode; } ``` HMIS-style action method: ```java 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: ```java public String patientCode; ``` Prefer a private attribute with public getters and setters: ```java 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. ```java private String patientName; private Department department; private Investigation investigation; ``` Private helper method: ```java 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: ```java @Override protected EntityManager getEntityManager() { return entityManager; } ``` Facade example: ```java @Stateless public class PatientInvestigationFacade extends AbstractFacade { @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: ```java 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: ```java String internalCode; ``` Method example: ```java void clearTemporaryData() { } ``` A default member can only be accessed by classes in the same package. HMIS-style example: ```java 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: ```java private String patientCode; private Date createdAt; private Department department; private boolean retired; ``` Avoid: ```java public String patientCode; public Date createdAt; ``` Use public getters and setters: ```java public String getPatientCode() { return patientCode; } public void setPatientCode(String patientCode) { this.patientCode = patientCode; } ``` --- ## Access Modifiers for Methods ### Public method ```java public void process() { } ``` Can be called by other classes or XHTML pages. ### Private method ```java private boolean validateFilters() { return fromDate != null && toDate != null; } ``` Can only be called inside the same class. ### Protected method ```java protected EntityManager getEntityManager() { return entityManager; } ``` Can be called by child classes and classes in the same package. ### Default method ```java void resetInternalState() { } ``` 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: ```java public class InvestigationReport { } ``` Default-access class: ```java class InvestigationReportHelper { } ``` 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. ```java 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: - `total` and `discount` are private. - Getters provide read access. - Setters provide controlled write access. - Validation prevents invalid values. - `calculateNetTotal()` is public behaviour. --- ## HMIS-Style Example ```java public class InvestigationReportData { private Date fromDate; private Date toDate; private Department laboratory; private Investigation investigation; private List 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 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. ```java private String patientName; private String nationalIdentityCardNumber; private String diagnosis; private String investigationResult; private String prescriptionDetails; ``` Sensitive attributes should be private. Avoid: ```java public String diagnosis; ``` Prefer: ```java private String diagnosis; ``` Only provide a public getter when the information must be accessed: ```java 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. --- ## Common Mistakes ### Public attributes Avoid: ```java public String patientName; ``` Use: ```java private String patientName; ``` ### Private method needed by XHTML Incorrect: ```java private void process() { } ``` Correct: ```java public void process() { } ``` ### Public internal helper method Avoid: ```java public boolean isDateRangeValid() { } ``` when only the same class uses it. Prefer: ```java private boolean isDateRangeValid() { } ``` ### Protected attributes without a reason Avoid: ```java protected Department department; ``` Prefer: ```java private Department department; ``` ### Using default access accidentally ```java String patientCode; ``` If the attribute should be private, write: ```java private String patientCode; ``` --- ## Best Practices 1. Keep attributes private. 2. Use public getters and setters only when required. 3. Keep internal helper methods private. 4. Use protected methods only for inheritance. 5. Use default access only for package-level design. 6. Avoid public mutable attributes. 7. Do not expose sensitive patient information unnecessarily. 8. Use the smallest access level required. 9. Do not make everything public. 10. Review access levels when refactoring code. --- ## Summary Java has four access levels: ```text private default protected public ``` From most restricted to least restricted: ```text private → default → protected → public ``` Recommended HMIS usage: ```java 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.