CSC108 Lecture Notes (Meng Sun)

The Keyword "Static"

static

Understanding Instance and Class Members

Instance Variables Class Variables
  Instance Methods and Class Methods
 
Instance Methods Class Methods
can acess
instance variables
yes no
can  access 
class variables
yes yes
can be accessed through only objects objects or the class itself

 

Example Program -- using "static" variable and method

Here is an example program which uses "static" variable and methods to read String inputs.
//-------------------------------------
// Read_color:
//    Use static class variable
//      static BufferedReader in
//    to read color name input.
//-------------------------------------

import java.io.*;

class Read_color
{
   //---------------
   // Variables
   //--------------
   static BufferedReader in = new BufferedReader(new
                        InputStreamReader(System.in));

   //-------------
   // Methods
   //-------------
   public static void main (String[] args) throws IOException
   {
      String color;

      color = get_color();
      System.out.println ("The color you entered is -- "
                                    + color);

      color = get_color();
      System.out.println ("The color you entered is -- "
                                    + color);
   }

   public static String get_color() throws IOException
   {
      System.out.print("Enter the name of a color --> ");
      String line = in.readLine();
      return line;
   }
}

  A Note on Programming Style -- Initializing Instance Variables

In the Fruit class example above, we used the constructor to initialize the instance variables for each new object. There are a number of advantages to this programming practice --