Building Java Programs Chapter 8 Lecture 8 3
Building Java Programs Chapter 8 Lecture 8 -3: Encapsulation; Homework 8 (Critters) reading: 8. 3 - 8. 4 Copyright 2010 by Pearson Education 1
Encapsulation reading: 8. 4 Copyright 2010 by Pearson Education 22
Encapsulation encapsulation: Hiding implementation details from clients. Encapsulation forces abstraction. separates external view (behavior) from internal view (state) protects the integrity of an object's data Copyright 2010 by Pearson Education 3
Private fields A field that cannot be accessed from outside the class private type name; Examples: private int id; private String name; Client code won't compile if it accesses private fields: Point. Main. java: 11: x has private access in Point Copyright 2010 by Pearson Education 4
Accessing private state // A "read-only" access to the x field ("accessor") public int get. X() { return x; } // Allows clients to change the x field ("mutator") public void set. X(int new. X) { x = new. X; } Client code will look more like this: System. out. println(p 1. get. X()); Copyright 2010 by Pearson Education 5
Point class, version 4 // A Point object represents an (x, y) location. public class Point { private int x; private int y; public Point(int initial. X, int initial. Y) { x = initial. X; y = initial. Y; } public int get. X() { return x; } public int get. Y() { return y; } public double distance. From. Origin() { return Math. sqrt(x * x + y * y); } public void set. Location(int new. X, int new. Y) { x = new. X; y = new. Y; } } public void translate(int dx, int dy) { set. Location(x + dx, y + dy); } Copyright 2010 by Pearson Education 6
Benefits of encapsulation Abstraction between object and clients Protects object from unwanted access Example: Can't fraudulently increase an Account's balance. Can change the class implementation later Example: Point could be rewritten in polar coordinates (r, θ) with the same methods. Can constrain objects' state (invariants) Copyright 2010 by Pearson Education 7
The keyword this reading: 8. 3 Copyright 2010 by Pearson Education 88
The this keyword this : Refers to the implicit parameter inside your class. (a variable that stores the object on which a method is called) Refer to a field: this. field Call a method: this. method(parameters); One constructor this(parameters); can call another: Copyright 2010 by Pearson Education 9
Variable shadowing: 2 variables with same name in same scope. Normally illegal, except when one variable is a field. public class Point { private int x; private int y; . . . // this is legal public void set. Location(int x, int y) {. . . } Copyright 2010 by Pearson Education 10
Fixing shadowing public class Point { private int x; private int y; . . . public void set. Location(int x, int y) { this. x = x; this. y = y; } } Inside set. Location, To refer to the data field x, To refer to the parameter x, Copyright 2010 by Pearson Education say this. x say x 11
Calling another constructor public class Point { private int x; private int y; public Point() { this(0, 0); constructor } // calls (x, y) public Point(int x, int y) { this. x = x; this. y = y; } } . . . Copyright 2010 by Pearson Education 12
Homework 8: Critters reading: HW 8 assignment spec Copyright 2010 by Pearson Education 13 13
Critters A simulation world with animal objects with behavior: eating food fight animal fighting get. Color color to display get. Move movement to. String letter to display You must implement: Ant Bird Hippo Copyright 2010 by Pearson Education 14
A Critter subclass public class name extends Critter {. . . } extends Critter tells the simulator your class is a critter an example of inheritance Write some/all 5 methods to give your animals behavior. Copyright 2010 by Pearson Education 15
How the simulator works When you press "Go", the simulator enters a loop: move each animal once (get. Move), in random order if the animal has moved onto an occupied square, fight! if the animal has moved onto food, ask it if it wants to eat Key concept: The simulator is in control, NOT your animal. Example: get. Move can return only one move at a time. get. Move can't use loops to return a sequence of 16 Copyright 2010 by Pearson Education
Critter exercise: Cougar Write a critter class Cougar (the dumbest of all animals): Method Behavior constructor public Cougar() eat Always eats. fight Always pounces. get. Color Blue if the Cougar has never fought; red if he has. get. Move Walks west until he finds food; then walks east until he finds food; then goes west and repeats. "C" to. String Copyright 2010 by Pearson Education 17
Ideas for state You must not only have the right state, but update that state properly when relevant actions occur. Counting is helpful: How many total moves has this animal made? How many times has it eaten? Fought? Remembering recent actions in fields is helpful: Which direction did the animal move last? How many times has it moved that way? Did the animal eat the last time it was asked? Copyright 2010 by Pearson Education 18
Keeping state How can a critter move west until it finds food? public Direction get. Move() { while (animal has not eaten) { return Direction. EAST; } while (animal has not eaten a second time) { return Direction. EAST; } } private int moves; // total moves made by this Critter public Direction get. Move() { moves++; if (moves % 4 == 1 || moves % 4 == 2) { return Direction. WEST; } else { return Direction. EAST; } } Copyright 2010 by Pearson Education 19
Cougar solution import java. awt. *; // for Color public class Cougar extends Critter { private boolean west; private boolean fought; public Cougar() { west = true; fought = false; } public boolean eat() { west = !west; return true; } public Attack fight(String opponent) { fought = true; return Attack. POUNCE; }. . . Copyright 2010 by Pearson Education 20
Cougar solution. . . public Color get. Color() { if (fought) { return Color. RED; } else { return Color. BLUE; } } public Direction get. Move() { if (west) { return Direction. WEST; } else { return Direction. EAST; } } } public String to. String() { return "C"; } Copyright 2010 by Pearson Education 21
Testing critters Focus on one specific critter of one specific type Only spawn 1 of each animal, for debugging Make sure your fields update properly Use println statements to see field values Look at the behavior one step at a time Use "Tick" rather than "Go" Copyright 2010 by Pearson Education 22
Critter exercise: Snake Method Behavior constructor public Snake() eat Never eats fight always forfeits get. Color black get. Move 1 E, 1 S; 2 W, 1 S; 3 E, 1 S; 4 W, 1 S; 5 E, . . . to. String "S" Copyright 2010 by Pearson Education 23
Determining necessary fields Information required to decide what move to make? Direction to go in Length of current cycle Number of moves made in current cycle Remembering things you've done in the past: an int counter? a boolean flag? Copyright 2010 by Pearson Education 24
Snake solution import java. awt. *; // for Color public class Snake extends Critter { private int length; // # steps in current horizontal cycle private int step; // # of cycle's steps already taken public Snake() { length = 1; step = 0; } public Direction get. Move() { step++; if (step > length) { // cycle was just completed length++; step = 0; return Direction. SOUTH; } else if (length % 2 == 1) { return Direction. EAST; } else { return Direction. WEST; } } public String to. String() { return "S"; } } Copyright 2010 by Pearson Education 25
- Slides: 25