Encapsulation Flashcards

(6 cards)

1
Q

How to encapsulate a variables (fields)?

A

Declare the variables of a class as private

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How to read or write private fields?

A

Use getter and setter methods

Use public methods to access hidden fields, which act as gatekeepers

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Write a program using encapsulation to hide the name fields and use getter and setter to access it

A
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
		 }
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q
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>

A
public List<String> getAccessLog() { 
    return new ArrayList<>(this.accessLog); // Returns a new copy, protecting the original
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Unti tricky question 2 access modifiers and inheritance

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q
A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly