Java Reference
In-Depth Information
PITFALL: (continued)
and so it is illegal within the definition of a static method. (A static method has
no this .)
However, it is legal to invoke a static method within the defi nition of another static
method.
There is one way that you can invoke a nonstatic method within a static method:
if you create an object of the class and use that object (rather than this ) as the calling
object. For example, suppose myMethod() is a nonstatic method in the class MyClass .
Then, as we already discussed, the following is illegal within the defi nition of a static
method in the class MyClass :
myMethod();
However, the following is perfectly legal in a static method or any method definition:
MyClass anObject = new MyClass();
anObject.myMethod();
The method main is a static method, and you will often see code similar to this in the
main method of a class. This point is discussed in the Tip “You Can Put a main in
Any Class.”
TIP: You Can Put a main in Any Class
So far, whenever we have used a class in the main part of a program, that main
method was by itself in a different class definition within another file. However,
sometimes it makes sense to have a main method within a regular class definition.
The class can then be used for two purposes: It can be used to create objects in
other classes, or it can be run as a program. For example, you can combine the class
definition RoundStuff and the program RoundStuffDemo (both in Display 5.1 ) by
placing the main method inside the definition of the class RoundStuff , to obtain the
class definition shown in Display 5.2 .
Another example of a class with a main added is given in Display 5.3. Note that
in addition to the static method main , the class has another static method named
toCelsius . The class has both static and nonstatic methods. Note that the static
method toCelsius can be invoked without the class name or a calling object because
it is in another static method (namely main ) in the same class. However, the non-
static method toString requires an explicit calling object ( temperatureObject ).
Java requires that a program's main method be static. Thus, within a main method,
you cannot invoke a nonstatic method of the same class (such as toString ) unless
you create an object of the class and use it as a calling object for the nonstatic method.
You do not want to place just any main method in a class defi nition that is to be
used as a regular class to create objects. One handy trick is to place a small diagnostic
program in a main method that is inside of your class defi nition.
 
Search WWH ::




Custom Search