150 likes | 257 Views
MBCS Chapter2. Analysis Question sets 4-6. Fish. Notice the line Implements Locatable In the definition for Fish class. Fish accessor methods. Id Environment Color Location Direction isInEnv toString. isInEnv. Tests Is the fish in this environment? At the expected location?
E N D
MBCS Chapter2 Analysis Question sets 4-6
Fish Notice the line Implements Locatable In the definition for Fish class
Fish accessor methods • Id • Environment • Color • Location • Direction • isInEnv • toString
isInEnv • Tests • Is the fish in this environment? • At the expected location? • Compares what the fish thinks to what the environment thinks • If not = inconsistent
Public boolean isInEnv() { return (environment().objectAt(location()) == this); } this = the current object Meaning = is this fish recognized by the environment to be at the location where it thinks it is?
The Bounded Environment • Which methods could possibly create an inconsistent state? • numRows() • numCOls() • isValid(Location loc) • numObjects() • allObjects() • isEmpty() Think about it! …. But wait, there are more…..
Which methods could possibly create an inconsistent state? • objectAt(Location loc) • toString() • Add(Locatable obj) • Remove(Locatable obj) • recordMove(Locatable obj, Location, oldLoc)
Set 4 • Look at Fish initialize method. • Last step = add fish to theEnv • Environment receives fish, including location • Adds only if location not full • Fish & environment are in agreement • If a fish is removed from it’s environment (eaten or dies) it still “thinks” it’s at a certain location, but it’s not. • = inconsistent state
Why? • Why does act check to see if the fish is still in the environment and the call move? • Why not get rid of act and just use move? • Eventually fish breed, die, etc… they do much more than just move. • Makes it easy to override specific methods of behavior, not just moving.
Set 5 • True, true • False, false • False, true
Set 6 • neighborsOf returns all valid neighboring locations • Not just empty • emptyNeighbors code could have been included in nextLocation • BUT GOOD OOP = each method does 1 well-defined task • Putting emptyNeighbors in nextLoaction would have made it overly complicated.
Do Exercise 3 • Import java.util.ArrayList; • Public class Ch2Ex3 • { • Construct an environment and some fish • To get answers: • Create 3 locations • Create 3 arraylists of the neighbors of the locations • Display number of neighbors and locations using loops. • } // it should be easy to figure out which other locations have the same number of neighbors.