5.6 Writing Methods

  • Procedural Abstraction
    • allows us to name a block of code as a method and call it whenever we need it, abstracting away the details of how it works
    • Benefits:
      • organize our code by function
      • reduce its complexity
      • reduce the repetition of code
        • reuse code by putting it in a method and calling it whenever needed.
      • helps with debugging and maintenance
        • changes to that block of code only need to happen in one place
  • When you see repeated code, that is a signal for you to make a new method!

Three steps to creating and calling a method:

1) Object of the Class: Declare an object of your class in the main method or from outside the class.

// Step 1: declare an object in main or from outside the class


Classname objectName = new Classname();
|   Classname objectName = new Classname();
cannot find symbol
  symbol:   class Classname

|   Classname objectName = new Classname();
cannot find symbol
  symbol:   class Classname

2) Method Call: whenever you want to use the method, call objectName.methodName();

// Step 2: call the object's method


objectName.methodName();

3) Method Definition: write the method’s header and body code like below:

// Step 3: Define the method in the class


// method header
public void methodName()
{
      // method body for the code
}

Identify Repetited Code

public static void main(String args[]) {
        System.out.print("Monday");
        System.out.println ("Code code code!");
        System.out.print("Tuesday");
        System.out.println ("Code code code!");
        System.out.print("Wednesday");
        System.out.println ("Code code code!");
        System.out.print("Thursday");
        System.out.println ("Code code code!");
        System.out.print("Friday");
        System.out.println ("Code code code!");
    }

repetited line:

System.out.println ("Code code code!")

public void code(){

}

Parameters

We can make methods even more powerful and more abstract by giving them parameters for data that they need to do their job.

class ClassName {
    // static variable
    public static type variableName;
  
    // static method
    public static returnType methodName(parameters) {
          // implementation not shown
    }
  }
  // To call a static method or variable, use the Class Name
  System.out.println(ClassName.staticVariable);
  ClassName.staticMethod();
Static methods Static variables
include the keyword static before their name in the header or declaration, can be public or private include the keyword static before their name in the header or declaration, can be public or private
are associated with the class, not objects of the class belong to the class, with all objects of a class sharing a single static variable
cannot access or change the values of instance variables, but they can access or change the values of static variables used with the class name and the dot operator, since they are associated with a class, not objects of a class
cannot call non-static methods

Static methods and variables include the keyword static before their name in the header or declaration. They can be public or private.

Static variables belong to the class, with all objects of a class sharing a single static variable.

Static methods are associated with the class, not objects of the class.

Static variables are used with the class name and the dot operator, since they are associated with a class, not objects of a class.

Static methods cannot access or change the values of instance variables, but they can access or change the values of static variables.

Static methods cannot call non-static methods.

Practice

Consider the following class, which uses the instance variable dollars to represent the money in a wallet in dollars.

The putMoneyInWallet method is intended to increase the dollars in the wallet by the parameter amount and then return the updated dollars in the wallet. Which of the following code segments should replace missing code so that the putMoneyInWallet method will work as intended?

public class Wallet
{
    private double dollars;

    public double putMoneyInWallet(int amount)
    {
        /* missing code */
    }
}
A.
amount += dollars;
return dollars;
B.
dollars = amount;
return amount;
C.
dollars += amount;
return dollars;
D.
dollars = dollars + amount;
return amount;
E.
amount = dollars + amount;
return dollars;
public class Song
{

  /** Verse - prints out a verse of the song
   * @param number - a String like "one", "two", etc.
   * @param rhyme - a String like "thumb", "shoe", etc.
   */
   public void verse(String number, String rhyme)
   {
     System.out.println("This old man, he played " + number);
     System.out.println("He played knick knack on my " + rhyme);
   }

  // The chorus method
  public void chorus()
  {
     System.out.println("With a knick knack paddy whack, give a dog a bone.");
     System.out.println("This old man came rolling home.");
  }

  public static void main(String args[])
  {
      Song mySong = new Song();
      mySong.verse("one", "thumb");
      mySong.chorus();
      mySong.verse("two", "shoe");
      mySong.chorus();
  }
}

Song.main(null);
This old man, he played one
He played knick knack on my thumb
With a knick knack paddy whack, give a dog a bone.
This old man came rolling home.
This old man, he played two
He played knick knack on my shoe
With a knick knack paddy whack, give a dog a bone.
This old man came rolling home.
//The Old Man Song
public static void main(String args[]) {
    System.out.println("This old man, he played one.");
    System.out.println("He played knick knack on my thumb. ");
    System.out.println("With a knick knack paddy whack, give a dog a bone.");
    System.out.println("This old man came rolling home.");
    System.out.println("This old man, he played two.");
    System.out.println("He played knick knack on my shoe. ");
    System.out.println("With a knick knack paddy whack, give a dog a bone.");
    System.out.println("This old man came rolling home.");
}
//chorus() method definition
public void chorus()
{
      System.out.println("With a knick knack paddy whack, give a dog a bone.");
      System.out.println("This old man came rolling home.");
}
//chorus() method call
mySong.chorus();

Consider the class Temperature below which has a static variable. What is the output of the main method below?

public class Temperature
{
   private double temperature;
   public static double maxTemp = 0;

   public Temperature(double t)
   {
        temperature = t;
        if (t > maxTemp)
            maxTemp = t;
   }

   public static void main(String[] args)
   {
        Temperature t1 = new Temperature(75);
        Temperature t2 = new Temperature(100);
        Temperature t3 = new Temperature(65);
        System.out.println("Max Temp: " + Temperature.maxTemp);
   }
 }

A. Max Temp: 0

B. There is a compiler error because the static variable maxTemp cannot be used inside a non-static constructor.

C. Max Temp: 100

D. Max Temp: 75

E. Max Temp: 65

hints:

maxTemp is changed in each call to the Temperature() constructor

Non-static methods and constructors can use any instance or static variables in the class