CSCI111: Chapter 4

CSCI 111: Notes Chapter 4
Writing Classes - Anatomy of a Method


Expressions

First a reminder of how memory works and calculations/programs in Chapter 2 notes

Methods

(these notes are not in the text)

Local Variables

Sometimes it is easier (and/or more clear what is happening) to define new variables inside of a method

Look at both TriangleMethodDemo.java with its html page

Could you define another method for making triangles just giving three points? Discuss

Look at the code for lab 4: ComputeFigure.java and trace it.

return and results

To get results out of a method (the text calls these queries as compared to commands) we need the return Notice that when a call to a method returns something, you cannot just call the method with
areaRectangle(30,40);
Why not?

Building on methods

We have a handy drawTriangle method. Use it to build a house.
and its html page

Methods return to who they were invoked from. So, trace the program.
Here is the code numbered so we can follow the line numbers for the trace


We now have the understanding to provide a basic template that all classes fit. One last thing though:

Java programs that do not run on a browser (i.e., not Applets) need a main method to get them started. The main method

is the top-level method that initiates execution of a system.
Note that the main code needs to explicitly instantiate the class and call a method to get it started (applets don't have to do this).

The book focuses on these (applications), but I will continue to show both.


imports ... 

public class ClassName extends  super  {

             // Declare and possibly set values for variables

  Instance and Class Variable declarations 

  private int instanceVariable;
  public static int classVariable;

             // Define Constructors (if none - looks at supers.  No return type)

   public ClassName (formal parameters) {

     code

  }
            // Define methods with no returned values

  public void methodName (formal parameters) {

     code

  }
            // Define methods with return values

  public returnType methodName (formal parameters) {

     code
     return ...   // returnType of value returned must match method signature

  }
}


Text examples:
code and exercises Ch 3, exercises Ch4