40 likes | 77 Views
Method invocation versus definition. “There is a difference between knowing the path and walking the path.” ~ Morpheus “There is a difference between defining a method and invoking a method.” ~ CSSE Prof. Method invocation versus definition.
E N D
Method invocation versus definition • “There is a difference between knowing the path and walking the path.” ~ Morpheus • “There is a difference between defining a method and invoking a method.” ~ CSSE Prof.
Method invocation versus definition • To define (write) a method means to write its code • The code is a recipe to follow when the method runs • Methods often have parameters – information that comes into the method when it is run • To invoke (call, run) a method means to cause the method’s code to run • Sending it actual values to substitute for the formal parameters of the method • Example (on next slides)
Method invocation versus definition • To define (write) a method means to write its code • To invoke (call, run) a method means to cause the method’s code to run • Example (on next slide): • The NameDropper class in the blue box defines: • A field called myName to hold the NameDropper’s name to drop • A constructor called NameDropper that takes the name to store in the field • A method called transform that takes a phrase to tranform • The statements in the yellow box cause the NameDropper constructor and transform method to run • They each run several times, with different actual arguments substituted for the formal parameters in the NameDropper definition • These statements would themselves appear in some other class
public class NameDropper extends StringTransformer implements StringTransformable { private String myName; public NameDropper(String nameToUse) { this.myName = nameToUse; } public String transform(String thePhrase) { return this.myName + “says ” + thePhrase; }} Definition of the NameDropper class NameDropper person1, person2, person3; person1 = new NameDropper(“Calvin”); person2 = new NameDropper(“Hobbes”); person3 = new NameDropper(“lobster”); person1.transform(“you look funny today, Hobbes.”); person2.transform(“you looker even funnier.”); person1.transform(“no, YOU look funnier.”); person3.transorm(“I amd just a lonely lobster.”); Invoking the NameDropper constructor and transform method Questions?