Using Static Classes | Heaton Research

Using Static Classes

Get the entire book!
Java for the Beginning Programmer

Java contains a very useful class named Math. We have already used the Math class to obtain random numbers. What is very unique about the Math class is that every method is static. It is illegal to instantiate the Math class. For example, the following program is incorrect.

Important: DON’T DO THIS! It is illegal to instantiate the Math class.

public static void main(String args[])
{
  Math m = new Math(); // Never do this!
  System.out.println(m.max(1,2));
}

If you would like to use the max method of Math, simply call it directly.

public static void main(String args[])
{
  System.out.println(Math.max(1,2));
}

As you can see the max function is called directly from the Math class. This sort of call can be made on static functions/methods.

Copyright 2005-2008 by Heaton Research, Inc.