Java's Static Keyword

March 12, 2013

How well do you understand Java’s static keyword? I was surprised by its range of uses!

Class Methods

Methods using the static keyword are basically class methods, or methods that the class can utilize without being initialized. In Ruby, a class method is defined by using self before defining the name of the method:

class CoffeeMaker
  def self.make_coffee
    # Make me coffee!
  end
end

In this case, the self.make_coffee method can be called without creating a new instance of CoffeeMaker.

Java is similar in that all you need to do to make a method a class method is to prepend static to its definition:

public class CoffeeMaker {
  static void make_coffee() {
    // Make me coffee!
  }
}

Class Variables

Similar to class methods in Java, class variables (again, variables accessible without instantiating a new instance of a class) only require a prepended static keyword:

public class CoffeeMaker {
  static int modelNumber = 2013;
  public int unitNumber;
}

I included the instance variable unitNumber to the above code to show how a class variable might be useful. A coffee maker’s modelNumber could be the same for all the reproductions, regardless of how many times it’s instantiated. The unitNumber, however, would be unique to each coffee maker, and would therefore warrant being an instance variable, only available after a coffee maker object has been instantiated.

In Ruby, class variables are denoted by two @ symbols before the variable name and instance variables with one @ symbol:

class CoffeeMaker
  @@model_number = 2013_XTREME_COFFEMAKER

  def initialize
    @unit_number = 00001
  end
end

Note: I’ve never seen Ruby class variables used in the wild. My understanding is that they are just confusing and that there can be unintended side-effects involved with shared state. In short, use sparingly or not at all!

Constants

You can also combine the static and final keywords to make constants, or values that never change once set:

public class CoffeeMaker {
  static final String BRAND = "CoffeMaestro";
  // Coffee-making code here
}

In Ruby, constants can be defined outside of a class:

BRAND = "CoffeMaestro"

class CoffeeMaker
  # I can use the BRAND constant here!
end

In an IRB session, you will get errors when you redefine a constant, though it does let you do it:

1.9.3p362 :001 > BRAND = "CoffeMaestro"
 => "CoffeMaestro" 
1.9.3p362 :002 > BRAND = "CoffeeMaestro"
(irb):2: warning: already initialized constant BRAND
 => "CoffeeMaestro"
1.9.3p362 :003 >   BRAND
 => "CoffeeMaestro" 

Note: It’s convention in both Ruby and Java to write out constant names in all caps!