The RetroBug problem from the 2012 AP Computer Science Exam tests your understanding of inheritance by asking you to extend the Bug class from the GridWorld Case Study.
Review the RetroBug free response solution with AP CS Tutor Brandon Horn.
RetroBug
public class RetroBug extends Bug { private Location prevLoc; private int prevDir; public void act() { prevLoc = getLocation(); prevDir = getDirection(); super.act(); } public void restore() { if(prevLoc != null) { setDirection(prevDir); Actor atPrev = getGrid().get(prevLoc); if(atPrev == null || atPrev instanceof Flower) moveTo(prevLoc); } } }
2012 AP CS Exam Free Response Solutions |
this.setDirection(this.prevDir);
should be outside the if (location != null) loop. the bug should always go back to the original direction.
The problem stated that
restore
should have no effect if it is run before the first run ofact
. This would not be true if the call tosetDirection
was outside the check. Specifically, the direction of the bug would be set to the value ofprevDir
(0 unless explicitly initialized to something else) ifrestore
is run beforeact
.Could you please explain in detail how the restore() method is working?
restore
uses the RetroBug’s instance fields to restore the bug’s direction and (possibly) location to their values before its last move.If
restore
was run prior to the first run ofact
,prevLoc
would benull
. The firstif
statement ensures that the bug does not change its direction or attempt to move ifrestore
is run prior to the first run ofact
.The second
if
statement ensure that the previous location is empty or is occupied by a flower.In this program, how do I understand where to use the this keyword?
Please also explain the function of:
Actor atPrev = this.getGrid().get(this.prevLoc);
The
RetroBug
is only supposed to return to its previous location if the location is empty or contains aFlower
. The line you mentioned obtains theActor
atprevLoc
ornull
if the location is empty.Why is this called before all the variables? http://www.skylit.com/beprepared/x2012a2.html is another solutions guide, and it never calls this
The Java keyword
this
refers to the current object. It can be used for a variety of purposes. The use inRetroBug
is optional.When is the restore method called? The act method restore previous Location and Direction, but when is the method restore called for RetroBug? Or is it unnecessary?
restore
is not called within the question. It is a method that could be run by a class that usesRetroBug
.