Title: Computer Science 209
1Computer Science 209
2What Is Encapsulation?
- The state of an object the values of its
instance variables can be modified only by
running that objects methods - We get encapsulation by declaring a variable as
private
3Why Encapsulate?
- Security avoid side effects
- Modularity and simplicity reduce the number of
interactions - Responsibility enforce ownership and division
of labor in a system
4Enforcement private Visibility
public class MyClass private String name
public ListltBookgt books
All instance variables should have private
visibility Dont make an instance variable
public because you think it will make it easier
for clients to access
5Enforcement Immutability
public class MyClass private String name
public void setName(String name)
Avoid supplying mutator methods unless they are
absolutely necessary Classes like String are
immutable
6Enforcement Immutability
public class MyClass private ListltBookgt
books public ListltBookgt getBooks()
return books
Avoid returning references to mutable objects
7Enforcement Immutability
ListltSomethinggt A new ArrayListltSomethinggt() L
istltSomethinggt B new ArrayListltSomethinggt() A.
addAll(B) // A is implicit, B is explicit
// A is modified, B is not public void
modifyList(ListltSomethinggt x) x.clear()
Avoid mutations on explicit parameters
8The Law of Demeter
- A method should use only
- Instance fields of its class
- Parameters
- Objects that it constructs with new
- Dont operate on global objects or on objects
that are part of the internal state of another
object