Class 1, Part 2 |
Intro to Java 30-IT-396 |
|
Static Methods, Factory Methods
-
Just like static fields, static methods belong to the class, not its objects.
-
Thus, you do not need to declare an object to use the method.
-
This is inherently more efficient, because objects take up space in memory.
-
If the method does not access object-specific fields, or when it only accesses
static fields, it can (and should) be declared static.
-
Example: String strNumber = Integer.parseInt(intNumber); converts
the int intNumber to a String, strNumber, via the Integer
class. But notice that you do not need to instantiate an Integer
object to use it.
-
For the Java Foundation Classes, you can tell static methods because they
say
so.
-
Remember our discussion about Factory Methods?
-
A factory method is a static method that returns an instance of an object.
-
This means that the constructor is called internally, by that method, and
the constructor is usually marked private.
-
Thus, you cannot get an object by NumberFormat percent = new NumberFormat(),
you must get it by NumberFormat percent = NumberFormat.getPercentInstance();
-
Why? What are the advantages?
-
What is a static method we have been using all along in this class?
What is its purpose?
Method Parameters


Created by: Brandan
Jones January 4, 2002