2

How can jvm enter in default class:

class try1
{
public static void main(String args[])
{
    ...
}
}

In it how does JVM access this method?

In packages, if a class is 'default' its public methods cant be accessed from outside the package, so how does jvm enter this class?

3 Answers3

10

It is not JVM itself who invokes main method. This is rather a job of Java launcher, i.e. java.exe.
Java launcher is a small program written in C that uses regular JNI functions:

  1. JNI_CreateJavaVM to create a new instance of JVM and to obtain an instance of JNIEnv;
  2. JNIEnv::FindClass to locate the main class specified in the command line;
  3. JNIEnv::GetStaticMethodID to find public static void main(String[]) method in class #2.
  4. JNIEnv::CallStaticVoidMethod to invoke the method found in #3.

In fact, JNI allows you to work with all classes, methods and fields, even with private modifier.

apangin
  • 92,924
  • 10
  • 193
  • 247
0

First of all the JVM does not enter the method, it invokes (calls) it (yes, it matters). The keyword public declares that the method can be accessed from anywhere (different packages); the static keyword declares that you can call the method without instatiating the class (among other things) and as far as I know the class that contains the main method is always public.

George Daramouskas
  • 3,720
  • 3
  • 22
  • 51
0

You explicitly told java what class to load on the command line or in a .jar's Manifest if you're running an executable jar.

The Java Specification Chapter 12 goes briefly into what happens when the JVM starts up. (The JVM Specification Chapter 5 covers it in more detail.)

In short: java try1 will load the try1 class, then link, verify, resolve, and initialize it.

Once that's done, it will look for a main method that is public, static, and void that accepts an array of Strings, then it will execute that method.

The JVM doesn't care that your class wasn't public. As the first class loaded, it is the current compilation unit and initial access control is calculated from it.

Powerlord
  • 87,612
  • 17
  • 125
  • 175