cs 106a, lecture 15 events and memory -...
TRANSCRIPT
Thisdocumentiscopyright(C)StanfordComputerScienceandMartyStepp,licensedunderCreativeCommonsAttribution2.5License.Allrightsreserved.BasedonslidescreatedbyKeithSchwarz,MehranSahami,EricRoberts,StuartReges,andothers.
CS106A,Lecture15EventsandMemory
3
Plan for Today•Announcements•Review:Null,EventsandInstanceVariables•ExtraPractice:Googley Eyes•ABooleanAside•Memory•RevisitingWhack-A-Mole
4
Plan for Today•Announcements•Review:Null,EventsandInstanceVariables•ExtraPractice:Googley Eyes•ABooleanAside•Memory•RevisitingWhack-A-Mole
5
Plan for Today•Announcements•Review:Null,EventsandInstanceVariables•ExtraPractice:Googley Eyes•ABooleanAside•Memory•RevisitingWhack-A-Mole
6
NullNullisaspecialvariablevaluethatobjects canhavethatmeans“nothing”.Primitives cannotbenull.
Ifamethodreturnsanobject,itcanreturnnull tosignify“nothing”.(justsayreturn null;)
// may be a GObject, or null if nothing at (x, y)GObject maybeAnObject = getElementAt(x, y);
Objectshavethevaluenull beforebeinginitialized.
Scanner myScanner; // initially null
7
NullYoucancheckifsomethingisnullusing==and!=.
// may be a GObject, or null if nothing at (x, y)GObject maybeAnObject = getElementAt(x, y);if (maybeAnObject != null) {
// do something with maybeAnObject} else {
// null – nothing at that location}
8
NullCallingmethodsonanobjectthatisnull willcrashyourprogram!
// may be a GObject, or null if nothing at (x, y)GObject maybeAnObject = getElementAt(x, y);if (maybeAnObject != null) {
int x = maybeAnObject.getX(); // OK} else {
int x = maybeAnObject.getX(); // CRASH!}
9
Events•event:Someexternalstimulusthatyourprogramcanrespondto.
•event-drivenprogramming:Acodingstyle(commoningraphicalprograms)whereyourcodeisexecutedinresponsetouserevents.
10
Events
public void run() {// Java runs this when program launches
}
public void mouseClicked(MouseEvent event) {// Java runs this when mouse is clicked
}
public void mouseMoved(MouseEvent event) {// Java runs this when mouse is moved
}
11
Types of Mouse Events• Therearemanydifferenttypesofmouseevents.
– Eachtakestheform:public void eventMethodName(MouseEvent event) { ...
Method DescriptionmouseMoved mousecursormovesmouseDragged mousecursormoveswhilebuttonishelddownmousePressed mousebuttonispresseddownmouseReleased mousebuttonisliftedupmouseClicked mousebuttonispressedandthenreleasedmouseEntered mousecursorentersyourprogram'swindowmouseExited mousecursorleavesyourprogram'swindow
12
MouseEvent Objects
•AMouseEvent containsinformationabouttheeventthatjustoccurred:
Method Descriptione.getX() thex-coordinateofmousecursorinthewindowe.getY() they-coordinateofmousecursorinthewindow
15
Doodlerpublic void mouseDragged(MouseEvent event) {
double mouseX = event.getX();double mouseY = event.getY();double rectX = mouseX – SIZE / 2.0;double rectY = mouseY – SIZE / 2.0;GRect rect = new GRect(rectX, rectY, SIZE, SIZE);rect.setFilled(true);add(rect);
}
Whatifwewantedthesame GRect totrackthemouse,insteadofmakinganewoneeachtime?
16
Instance Variablesprivate type name; // declared outside of any method
• Instancevariable:Avariablethatlivesoutsideofanymethod.– Thescope ofaninstancevariableisthroughoutanentirefile(class).
– Usefulfordatathatmustpersistthroughouttheprogram,orthatcannotbestoredaslocalvariablesorparameters(eventhandlers).
– Itisbadstyletooveruseinstancevariables
18
Whack-A-MoleWeusedinstancevariablesandeventstomakeWhack-A-Mole!• Amoleshouldappeareverysecondatarandomlocation,andstoponcetheuserhasgottenatleast10points.
• Iftheuserclicksamole,removeitandincreasetheirscoreby1• ThereshouldbeaGLabel intheleftcornershowingtheirscore
19
Exception• Iftheuserclicksanareawithnomole,theprogramcrashes.
– AprogramcrashinJavaiscalledanexception.– Whenyougetanexception,Eclipseshowsrederrortext.– Theerrortextshowsthelinenumberwheretheerroroccurred.– Whydidthiserrorhappen?– Howcanweavoidthis?
20
Whack-A-Null?public void mouseClicked(MouseEvent event) {
double mouseX = event.getX();double mouseY = event.getY();GObject mole = getElementAt(mouseX, mouseY);
remove(mole);score++;scoreLabel.setText("Score: " + score);
}
21
Whack-A-Null?public void mouseClicked(MouseEvent event) {
double mouseX = event.getX();double mouseY = event.getY();GObject mole = getElementAt(mouseX, mouseY);
remove(mole);score++;scoreLabel.setText("Score: " + score);
}
Problem:molemaybenulliftheuserdoesn’tclickonamole!RemovingnullwillcrashL
22
Whack-A-Mole!public void mouseClicked(MouseEvent event) {
double mouseX = event.getX();double mouseY = event.getY();GObject mole = getElementAt(mouseX, mouseY);
if (mole != null) {remove(mole);score++;scoreLabel.setText("Score: " + score);
}}
23
Revisiting DribbleCastleWewroteaprogramcalledDribbleCastle thatsimulateswetsandfallingandformingcoolshapes.
Butweleftoutonepart:howdowestoptheanimationifonedribblecollideswithanother?
24
DribbleCastleprivate void dropOneDribble() {
GOval dribble = makeDribble();add(dribble);
while (!hasHitBottom(dribble) && !hasHitSomethingElse(dribble)) {
dribble.move(0, Y_VELOCITY);pause(PAUSE_TIME);
}}
25
DribbleCastleprivate void dropOneDribble() {
GOval dribble = makeDribble();add(dribble);
while (!hasHitBottom(dribble) && !hasHitSomethingElse(dribble)) {
dribble.move(0, Y_VELOCITY);pause(PAUSE_TIME);
}}
26
DribbleCastleprivate void dropOneDribble() {
GOval dribble = makeDribble();add(dribble);
while (!hasHitBottom(dribble) && !hasHitSomethingElse(dribble)) {
dribble.move(0, Y_VELOCITY);pause(PAUSE_TIME);
}}
27
hasHitSomethingElseprivate boolean hasHitSomethingElse(GOval dribble) {double checkX = dribble.getX()
+ dribble.getWidth() / 2.0;double checkY = dribble.getY()
+ dribble.getHeight() + 1;GObject hit = getElementAt(checkX, checkY);return hit != null;
}
28
hasHitSomethingElseprivate boolean hasHitSomethingElse(GOval dribble) {double checkX = dribble.getX()
+ dribble.getWidth() / 2.0;double checkY = dribble.getY()
+ dribble.getHeight() + 1;GObject hit = getElementAt(checkX, checkY);return hit != null;
} NeedtocheckoutsideoftheGOval itself!
Otherwise,getElementAt mayreturnthedribble.
Checkifsomethingishere
29
Plan for Today•Announcements•Review:Null,EventsandInstanceVariables•ExtraPractice:Googley Eyes•ABooleanAside•Memory•RevisitingWhack-A-Mole
30
Extra Practice: GoogleyEyesLet’swriteaprogramcalledGoogleyEyes thatdrawseyeswhosepupilsfollowtheuser’smouseverticallyasitmovesaround.
31
Plan for Today•Announcements•Review:Null,EventsandInstanceVariables•ExtraPractice:Googley Eyes•ABooleanAside•Memory•RevisitingWhack-A-Mole
32
A Boolean AsideThereisonehelpfulpropertyofhowJavaevaluatesbooleanexpressions,calledshort-circuitevaluation.
Whenevaluatingboolean expressions,Javaonlyevaluatesasmuchoftheexpressionasitneedstoinordertoevaluateittobetrueorfalse.
34
A Boolean AsideString str = readLine("? "); // what about “”!
if (str.length() > 0 && str.charAt(0) == 'A') {...
}
35
A Boolean AsideString str = readLine("? "); // what about “”!
if (str.length() > 0 && str.charAt(0) == 'A') {...
}
36
A Boolean AsideString str = readLine("? "); // what about “”!
if (str.length() > 0 && str.charAt(0) == 'A') {...
}
Javaonlyexecutesthisifthefirstpartistrue!Thismeansitnevercrashes.
38
A Boolean AsideGObject obj = getElementAt(x, y); // what about null!
if (obj == null || obj.getX() == 0) {...
}
39
A Boolean AsideGObject obj = getElementAt(x, y); // what about null!
if (obj == null || obj.getX() == 0) {...
}
40
A Boolean AsideGObject obj = getElementAt(x, y); // what about null!
if (obj == null || obj.getX() == 0) {...
}
Javaonlyexecutesthisifthefirstpartisfalse!Thismeansitnevercrashes.
41
Plan for Today•Announcements•Review:Null,EventsandInstanceVariables•ExtraPractice:Googley Eyes•ABooleanAside•Memory•RevisitingWhack-A-Mole
Thisdocumentiscopyright(C)StanfordComputerScienceandMartyStepp,licensedunderCreativeCommonsAttribution2.5License.Allrightsreserved.BasedonslidescreatedbyKeithSchwarz,MehranSahami,EricRoberts,StuartReges,andothers.
Chapter 1: Birth
Thisdocumentiscopyright(C)StanfordComputerScienceandMartyStepp,licensedunderCreativeCommonsAttribution2.5License.Allrightsreserved.BasedonslidescreatedbyKeithSchwarz,MehranSahami,EricRoberts,StuartReges,andothers.
Once upon a time…
Thisdocumentiscopyright(C)StanfordComputerScienceandMartyStepp,licensedunderCreativeCommonsAttribution2.5License.Allrightsreserved.BasedonslidescreatedbyKeithSchwarz,MehranSahami,EricRoberts,StuartReges,andothers.
A few years later, the parents decided to have another variable.
55
…and its parents loved it very much.
GRect rect = new Grect(0, 0, 50, 50);
Weshouldmakeit….abig,strongGRect!
56
GRect rect = new Grect(0, 0, 50, 50);
Thatboxisn’tbigenoughto
storeeverything
aboutaGRect!
…but rect’s box was not big enough for an object!
57
…so they stored the information in a bigger box somewhere else.
GRect rect = new Grect(0, 0, 50, 50);
Seelocation
5
x=0,y=0width=50height=50...
Thisdocumentiscopyright(C)StanfordComputerScienceandMartyStepp,licensedunderCreativeCommonsAttribution2.5License.Allrightsreserved.BasedonslidescreatedbyKeithSchwarz,MehranSahami,EricRoberts,StuartReges,andothers.
Chapter 2: Friends
Thisdocumentiscopyright(C)StanfordComputerScienceandMartyStepp,licensedunderCreativeCommonsAttribution2.5License.Allrightsreserved.BasedonslidescreatedbyKeithSchwarz,MehranSahami,EricRoberts,StuartReges,andothers.
See “A Variable Love Story” for more...
66
rect also makes a new friend!
GRect r = new Grect(0, 0, 50, 50);
rect r
Seelocation5
Seelocation24
67
Rect also makes a new friend!
GRect r = new Grect(0, 0, 50, 50);
rect r
Seelocation5
Seelocation24
Hi!I’mr.
68
Rect also makes a new friend!
GRect r = new Grect(0, 0, 50, 50);
rect r
Seelocation5
Seelocation24
Itlookslikewehavethesamesize,
location,everything!
69
Rect also makes a new friend!
GRect r = new Grect(0, 0, 50, 50);
rect r
Seelocation5
Seelocation24
*blush*
Thisdocumentiscopyright(C)StanfordComputerScienceandMartyStepp,licensedunderCreativeCommonsAttribution2.5License.Allrightsreserved.BasedonslidescreatedbyKeithSchwarz,MehranSahami,EricRoberts,StuartReges,andothers.
But when they use == to compare values...
72
…something goes wrong.
if (rect == r) { // false!...
}
rect rSee
location5
Seelocation
24
…but…butIthoughtwehadsomuchin
common!
74
…something goes wrong.
if (rect == r) { // false!...
}
rect rSee
location5
Seelocation
24
Yousee,==compareswhatisineachvariable’s
box.
75
…something goes wrong.
if (rect == r) { // false!...
}
rect rSee
location5
Seelocation
24
Primitivesstoretheiractualvalueintheirbox.
76
…something goes wrong.
if (rect == r) { // false!...
}
rect rSee
location5
Seelocation
24
Butobjectsstorethelocation wherealltheir
informationlives.
77
…something goes wrong.
if (rect == r) { // false!...
}
rect rSee
location5
Seelocation
24
Thismeans==onobjectscomparestheirlocations,whichisnotwhat
wewanthere!
Thisdocumentiscopyright(C)StanfordComputerScienceandMartyStepp,licensedunderCreativeCommonsAttribution2.5License.Allrightsreserved.BasedonslidescreatedbyKeithSchwarz,MehranSahami,EricRoberts,StuartReges,andothers.
Chapter 3: Twins
85
Then, they wanted a twin for rect, too.
rectSee
location5
Wow,whatanawesomeGRect!Let’smakeanother
one.
86
…so rect2 was born!
rectSee
location5
Wow,whatanawesomeGRect!Let’smakeanother
one.
GRect rect2 = rect;
87
…so rect2 was born!
rectSee
location5
GRect rect2 = rect;
rect2See
location5
Wow,whatanawesomeGRect!Let’smakeanother
one.
88
GRect rect2 = rect;rect2.setColor(Color.BLUE);
…so rect2 was born!
rectSee
location5
rect2See
location5
Butlet’smakethisoneBLUE.
90
GRect rect2 = rect;rect2.setColor(Color.BLUE);
But something went wrong…
rectSee
location5
rect2See
location5
Cool,I’mblue!
91
GRect rect2 = rect;rect2.setColor(Color.BLUE);
But something went wrong…
rectSee
location5
rect2See
location5
Hey,whyamIblueTOO?
92
GRect rect2 = rect;rect2.setColor(Color.BLUE);
But something went wrong…
rectSee
location5
rect2See
location5
Yousee,whenyousetonevariableequaltoanother,thevalueinits
box iscopiedover.
93
GRect rect2 = rect;rect2.setColor(Color.BLUE);
But something went wrong…
rectSee
location5
rect2See
location5
Forprimitivevariables,thisjustmeanswecopytheirvalue.
94
GRect rect2 = rect;rect2.setColor(Color.BLUE);
But something went wrong…
rectSee
location5
rect2See
location5
Butforobjects,wecopyitslocation instead.
95
GRect rect2 = rect;rect2.setColor(Color.BLUE);
But something went wrong…
rectSee
location5
rect2See
location5
Therefore,bothrect andrect2thinktheirinformationisat
location5.
96
GRect rect2 = rect;rect2.setColor(Color.BLUE);
But something went wrong…
rectSee
location5
rect2See
location5
Whenyouchangeinformationforanobject,yougotoitslocationfirst,andthenupdate
theinformation.
97
GRect rect2 = rect;rect2.setColor(Color.BLUE);
But something went wrong…
rectSee
location5
rect2See
location5
Sincerect andrect2referencethesamelocation,whenyouchangeinformationfor
oneofthem,itchangesforboth!
Thisdocumentiscopyright(C)StanfordComputerScienceandMartyStepp,licensedunderCreativeCommonsAttribution2.5License.Allrightsreserved.BasedonslidescreatedbyKeithSchwarz,MehranSahami,EricRoberts,StuartReges,andothers.
Chapter 4: Leaving the Nest
100
college(x);
X grew up, and went to college.
x
27
Byeeveryone!I’mgoingtocollege.
We’llmissyou,honey!Don’tforgettocall!Don’tstayuptoolate!Watchoutforroguebicyclists!
102
private void college(int num) {num = 45;
}
x had an amazing college experience…
x
27num
45
run college
103
private void college(int num) {num = 45;
}
...but ultimately returned home the same.
x
27num
45
run college
105
college(x);println(x);
…but ultimately returned home the same.
x
27
I’mbaaaaack!AndI’mstill27.Ohhhh honey!You’ll
alwaysbeourlittle27.
106
college2(rect);
rect grew up too, and also went to college.
rectSee
location5
Byeeveryone!I’mgoingtocollege.
107
college2(rect);
rect grew up too, and also went to college.
rectSee
location5
Byeeveryone!I’mgoingtocollege.
Notyoutoo,rect!Weareemptynesters
now…
108
private void college2(GRect box) {...
}
rect grew up too, and also went to college.
run college2
rectSee
location5
boxSee
location5
109
private void college2(GRect box) {box.setColor(Color.YELLOW);
}
rect also had an amazing college experience…
run college2
rectSee
location5
boxSee
location5
111
private void college2(GRect box) {box.setColor(Color.YELLOW);
}
…but it returned home different.
run college2
rectSee
location5
boxSee
location5
I’myellow!
112
private void college2(GRect box) {box.setColor(Color.YELLOW);
}
…but it returned home different.
run college2
rectSee
location5
boxSee
location5
I’myellow!
Hey,whatgives!I’myellow
nowtoo!
113
college(rect);add(rect);
…but it returned home different.
rectSee
location5
I’mbaaaaack!ButnowI’myellow…
114
rectSee
location5
college(rect);add(rect);
…but it returned home different.
I’mbaaaaack!ButnowI’myellow…Ohmygosh….what
happened toyou??!
115
rectSee
location5
college(rect);add(rect);
…but it returned home different.
Yousee,whenavariableispassedasaparameter,thevalueinsideitsbox iscopied
andgiventothemethod.
116
rectSee
location5
college(rect);add(rect);
…but it returned home different.
Forprimitives,wemakeacopyoftheiractualvalue.Therefore,changestoaparameterdo
notaffecttheoriginal.
117
rectSee
location5
college(rect);add(rect);
…but it returned home different.
However,forobjectswemakeacopyoftheirlocation.Sochangestotheparameterdo
affecttheoriginal!
Thisdocumentiscopyright(C)StanfordComputerScienceandMartyStepp,licensedunderCreativeCommonsAttribution2.5License.Allrightsreserved.BasedonslidescreatedbyKeithSchwarz,MehranSahami,EricRoberts,StuartReges,andothers.
The End
119
Primitives vs. Objects• Primitivesstoretheiractualvalue intheirvariablebox.Youcancomparevalueswith==and!=,andtheoriginaldoesnotchangewhenpassedasaparameterandchanged.
• Objects storetheirlocation intheirvariablebox.Youcan’tcomparepropertiesofanobjectvia==,andtheoriginaldoeschangewhenpassedasaparameterandchanged.
• Primitivesarepassedbyvalue,Objectsarepassedbyreference
Thisdocumentiscopyright(C)StanfordComputerScienceandMartyStepp,licensedunderCreativeCommonsAttribution2.5License.Allrightsreserved.BasedonslidescreatedbyKeithSchwarz,MehranSahami,EricRoberts,StuartReges,andothers.
Practice – Chapter 2: Friends
121
Practicepublic void run() {
int x = 5;int y = 5;println(x == y);
}
Doesthisprintouttrue orfalse?
Thisdocumentiscopyright(C)StanfordComputerScienceandMartyStepp,licensedunderCreativeCommonsAttribution2.5License.Allrightsreserved.BasedonslidescreatedbyKeithSchwarz,MehranSahami,EricRoberts,StuartReges,andothers.
Practice – Chapter 3: Twins
124
Practicepublic void run() {
int x = 5;int y = x;y += 2;println(y);println(x);
}
Whatisprintedout?
125
Practicepublic void run() {
GOval oval = new GOval(0, 0, 50, 50);GOval oval2 = oval1;oval2.setColor(Color.BLUE);add(oval2);add(oval);
}
Whatcolorareovalandoval2?
Thisdocumentiscopyright(C)StanfordComputerScienceandMartyStepp,licensedunderCreativeCommonsAttribution2.5License.Allrightsreserved.BasedonslidescreatedbyKeithSchwarz,MehranSahami,EricRoberts,StuartReges,andothers.
Practice – Chapter 4: Leaving the Nest
127
Practicepublic void run() {
int x = 2;addFive(x);println(x);
}
private void addFive(int num) {num += 5;
}
Whatisprintedout?
128
Practicepublic void run() {
GRect rect = new GRect(0, 0, 50, 50);makeBlue(rect);add(rect);
}
private void makeBlue(GRect box) {box.setColor(Color.BLUE);
}
Whatcolorisrect?
129
Primitives vs. Objects
Primitivesstoretheiractualvalues.Objects storetheir
locations.
Thisaffectshowyourcodebehaves!
130
getElementAtgetElementAt returnsareference toanobject.
GRect rect = new GRect(0, 0, 50, 50);add(rect);...
GObject obj = getElementAt(25, 25);println(obj == rect);
Thisprintstrue!
131
Plan for Today•Announcements•Review:Null,EventsandInstanceVariables•ExtraPractice:Googley Eyes•ABooleanAside•Memory•RevisitingWhack-A-Mole
132
Revisiting Whack-A-MoleLet’srevisitourWhack-A-Moleprogramtoaddsomenewfunctionalityusingwhatwejustlearned.