Lecture 21 (Sherriff) - Methods

Lecture Date: Monday, March 2

Since the first day we began coding in this class, we have been using (or “calling”) methods to do various things:

Turtle Example
Turtle t = new Turtle();

Everything with ()s after it are methods. Methods are, in effect, verbs in our programs. They tell objects to do things, change their state somehow, or provide us with information. In the code above, we are telling the Turtle t to do some specific tasks. Each one of those tasks is a method.

The things inside the parentheses are called parameters or arguments. Parameters provide extra information to the method to tell it how to perform a method or what data it should act on. So, when we tell Turtle t to do forward(2), we are saying that 2 is important information in order for the method to execute properly.

Methods form the basis of many programs (as opposed to just having all your code in main) for several reasons:

  • Code reuse: Often you’ll have a bit of code you want to use over and over. Methods make that happen in a very nice way, while also allowing for modification with parameters.
  • Organization: It’s a lot easier to see what’s going on when you read code in main or somewhere else that has a set of methods saying what they do! Reading forward() and backward() in the Turtle code is completely understandable - having the code to do those things might not be.
  • Testing: Once you verify a method is correct and working, you can move on to other parts of your system.

There are a number of special kinds of methods that we will discuss. One of which is called a constructor method. See the Turtle t = new Turtle()? Turtle() isn’t really a command, per se. This method tells the system how to create a Turtle. A method that is used to create (or “boot up”) an object is called a constructor. You’ll see them with every complex type (except String…);

Another thing to know about methods is how parameters are passed into them.

  • Pass by Value: This is how primatives are passed (or given) to a method. A full copy of the primative (value and everything) is sent to the method. Any changes made to the variable passed in ARE NOT REFLECTED back where the method was called.
  • Pass by Reference: This is how complex types are passed to a method. A pointer (think “road sign”), which is a copy of the memory address of the object, is sent to the method. Any changes made to the variable passed in ARE REFLECTED back where the method was called.

We’ll also look at codingbat.com/java;

Examples: PassExamples.java