Computer Science 209 - PowerPoint PPT Presentation

1 / 8
About This Presentation
Title:

Computer Science 209

Description:

Computer Science 209 Encapsulation What Is Encapsulation? The state of an object the values of its instance variables can be modified only by running that ... – PowerPoint PPT presentation

Number of Views:49
Avg rating:3.0/5.0
Slides: 9
Provided by: KenL64
Category:

less

Transcript and Presenter's Notes

Title: Computer Science 209


1
Computer Science 209
  • Encapsulation

2
What 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

3
Why Encapsulate?
  • Security avoid side effects
  • Modularity and simplicity reduce the number of
    interactions
  • Responsibility enforce ownership and division
    of labor in a system

4
Enforcement private Visibility
public class GuessingGame private int
myNumber public boolean gameDone
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
5
Enforcement Immutability
public class Student private String name
public void setName(String name)
Avoid supplying mutator methods unless they are
absolutely necessary Classes like String are
immutable
6
Enforcement Immutability
public class MyClass private ListltBookgt
books public ListltBookgt getBooks()
return books
Avoid returning references to mutable objects
7
Enforcement 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
8
The 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
Write a Comment
User Comments (0)
About PowerShow.com