How to encapsulate a variables (fields)?
Declare the variables of a class as private
How to read or write private fields?
Use getter and setter methods
Use public methods to access hidden fields, which act as gatekeepers
Write a program using encapsulation to hide the name fields and use getter and setter to access it
public class NewStudent{
private String name;
public NewStudent(String name){
setName(name);
}
public String getName(){
return name;
}
public String setName(String newName){
this.name = newName
}
}import java.util.ArrayList;
import java.util.List;
public class EmployeeRecord {
// Internal state that is mutable
private List<String> accessLog = new ArrayList<>();
public EmployeeRecord() {
accessLog.add("Initialized at 08:00");
}
// Getter provides direct access to the internal list reference
public List<String> getAccessLog() {
return accessLog; // Line 1
}
}
How to made Line 1 more secure ?
~~~
// EmployeeRecord record = new EmployeeRecord();
// List<String> externalLog = record.getAccessLog();
// externalLog.clear(); // This will clear the log inside it
~~~</String>
public List<String> getAccessLog() {
return new ArrayList<>(this.accessLog); // Returns a new copy, protecting the original
}
Unti tricky question 2 access modifiers and inheritance