I. Introduction
The profile of a Java program takes this form:
public class Regards {
public static void main (String[] args){
System.out.println("All the best,");
}
}
public is the scope of the class (or method)
Regards is its name,
static is a modifier of the class (or method)
void is the type of the method main,
(String[] args) is a set of arguments or parameters.
The class is declared public. This modifier allow anyone to use it. Regards
is the name of the class. We save the file as Regards.java. To compile it, we use:
javac Regards.java
To execute the program, we use:
java Regards
If the class Regards is not public, we can access to
the result; but the function main must be public.
The main method is the principale method of a class. It is executed when we run the
class as an application. Inside, we can ceate objects, declare variables, evaluate
expressions, or invoke methods of classes.
This function main is static. That means the method belongs to its class
and does not involve an object (or instance) of the class. We can just create a new
object in it.
This method is also void. This is the type of the method. Void means that
it doesn't return any value.
II. Using a method
class TheBest {
static void Display (String Word){
System.out.println("This is the related word:" + Word);
}
public static void main (String[] args){
Display ("Regards");
System.out.println(" All the best of luck,");
}
}
Here the class contains another method that must be static because it is called by the
method main which is static.
Inside the function main, we use directly the method:
Display ("Regards");.
III. Calling a method from another class
Here are two classes that could be in the same file or in the same directory (package):
class TheBest {
static void Display (String Word){
System.out.println("This is the related word:" + Word);
}
}
class BestRegards {
public static void main (String[] args){
System.out.println("All the best,");
TheBest.Display ("Regards");
}
}
If we call the class TheBest (here to use Display function), we must
have TheBest.java in the same file or in the same directory than the current class.
We still do not need the classes to be public.
The class BestRegards uses the method Display of the first class TheBest, by writing :
FirstClass.MethodOfFirstClass. We have always to save the file with the name of the
class that contains the main function. In this example, save the
file as BestRegards.java.
Class.ItsMethod();
|