First of all, technicality: It is NOT true that the main method is also static. "You can define a non-static main method with any signature you choose; it simply will not be a valid entry point for a Java application.
As for the "static methods that should only use static variables", this is also NOT true. The key concept here is that static methods and fields are class specific and not specific instances. You simply cannot access the instance of the variable / method unless you actually have an instance of this class; This is a compilation error.
To be precise, without an instance, you cannot access the fields / methods of the instance. You can access static fields / methods without an instance. If you need to access field instances / methods from a static method, you must get an instance of this class one way or another, either simply by creating an instance of it, or by getting a link to it from a static field or method parameter.
Let's look at this simple example:
public static void main(String args[]) { System.out.println(args.length); }
length NOT a static field; This is the instance field of the array instances, which args is. The static main method is able to get this instance (and thus access its methods and instance fields) because it is passed as an argument.
In addition, println NOT a static method; This is an instance method of PrintStream instances. The static main method can get this instance by accessing the static out field of the System class.
Summarizing:
- A Java application entry point is a method that:
- called
main - -
public and static - returns
void and accepts String[] as a parameter
- The method named
main should not be a Java application entry point- (but itβs best to reserve this name for this purpose)
Moreover,
- Instance fields / methods can only be accessed through an instance
- Static fields / methods can be accessed without an instance.
- Static methods can get an instance of a class in one of the following ways:
- instantiation
new - passing it as an argument
- access to it through the
static field of the class - accepts it as the return value of the
static method of the class - catch it like thrown
Throwable
source share