Java Reference
In-Depth Information
A Class with No main() Method?
A common point of confusion that new OOP students of mine have arises when they
write a class that does not have main() method in it. A Java class without main() is not a
program.
For example, you cannot execute the Radio class. The Radio class is a description (albeit
a simple one) of an AM/FM radio. If you try to run Radio by entering the following command,
you will get an error message from the JVM, stating that no main() method was found:
java Radio
The Radio class is meant to be used by other classes that need a radio.
In a large Java application with dozens or even hundreds of classes, you might define
main() methods all over the place. However, it is likely that only one class has main() in it. If
the Java application is using other Java technologies such as Servlets or Enterprise JavaBeans,
no class will have a main() method in it.
On a similar note, just because Radio has a bunch of nice methods in it, it does not
mean that the methods are automatically invoked. If you want a method to execute, you
need to explicitly invoke it. Similarly, if you do not want a method to execute, don't invoke it.
For example, the ListenToRadio program creates a Radio object, but at no point is the
turnDown() method invoked. We could have invoked turnDown() if we wanted to because
it is available to us, but we do not have to and it is not invoked automatically at any point
in time.
Overloading Methods
Java allows a method to be overloaded. Method overloading occurs when a class
has two or more methods with the same name but different parameter lists.
Having more than one method with the same name might seem unnecessary,
but method overloading is used quite frequently in Java (and other program-
ming languages).
Method overloading is used most commonly with constructors, which are
discussed in the next section.
For example, the println() method that we used throughout the topic so far
is an overloaded method of the java.io.PrintStream class, as you can see by the
documentation of PrintStream shown in Figure 5.3.
Search WWH ::




Custom Search