130 likes | 138 Views
Explore the concepts of formal and actual parameters in Java methods, distinguishing between caller and callee roles. Discover implications of pass-by-value and pass-by-reference for parameter values.
E N D
Announcements Lab 2 Due Thursday 10pm 1 file per pair Last Time: methods logical reuseable parameterizable Announcements & Review Lecture 9: More on Methods
Today More on methods in a class Terminology method song calls method chorus song is the caller, chorus is the callee Formal parameters Actual parameters Call-by-value Call-by-reference Lecture 9: More on Methods
Formal Parametersin the callee method // formal parameters: width, length, s // the variable parameter names in the callee public void printBox(int width, int length, String s) { … } Shapes myshape = new Shapes(); for (int i = 0; i < 3; i++) { myshape.printBox(10, i, “*”); } Lecture 9: More on Methods
Actual Parametersin the caller method public void printBox(int width, int length, String s) { … } Shapes myshape = new Shapes(); for (int i = 0; i < 3; i++) { // actual parameters: 10, i, “*” // the parameters in the caller myshape.printBox(10, i, “*”); } Lecture 9: More on Methods
Does this make sense? public void printBox(int width, int length, String s) { width = 9; ... } Shapes myshape = new Shapes(); for (int i = 0; i < 3; i++) { myshape.printBox(10, i, “*”); } Lecture 9: More on Methods
BlueJ Examples • Try out changing a parameter Lecture 9: More on Methods
Call-by-ValueJava Semantics • Method cannot make externally visible changes to parameters • Can change it internally, but generally this is a bad bad idea. ;-) Lecture 9: More on Methods
Call-by-ReferenceSemantics • Method can make externally visible changes to parameters! • Algol 60 - declare a parameter as call-by-reference • What does this feature mean for actual parameters? Lecture 9: More on Methods
Call-by-ReferenceSemantics • Method can make externally visible changes to parameters! • Algol 60 - declare a parameter as call-by-reference • What does this feature mean for actual parameters? • method calls may change them Lecture 9: More on Methods
Getting aroundCall-by-Value • Method cannot make externally visible changes to parameters • How do we change state with methods then? Lecture 9: More on Methods
Getting aroundCall-by-Value • Method cannot make externally visible changes to parameters • for primitive types & objects • How do we change state with methods then? • return values, but Java only has one! • methods can make persistent changes to the fields of a parameter object object.color = pink; Lecture 9: More on Methods
BlueJ Examples • Let’s try a return value, and passing in an object as a parameter Lecture 9: More on Methods
More Questions? Lecture 9: More on Methods