0

The main method in java is defined as a public method, and this method is defined in a default class. lets say

class test{
    public static void main(String args[]){
        System.out.println("Hi");
    }
}

can you please explain how the JVM is able to access this main method as the class is default and it can be accessed only with in the package.

Moonbeam
  • 2,283
  • 1
  • 15
  • 17
mazem
  • 1
  • Moreover JVM is not your regular java class, isn't the entire specification and all access restrictions are implemented there. – Murali VP Jul 22 '11 at 19:19
  • If it worked THAT way, it'd be quite interesting to see how private methods should be called ;) – Voo Jul 22 '11 at 20:28

1 Answers1

4

You're thinking of the JVM as a bunch of Java code in some other package, which therefore couldn't access the main method hidden in your class with default accessibility. But it's not. The JVM is the virtual machine on which Java code is run; it decides what is and is not accessible to other Java code. In particular, it can run whichever methods it likes, regardless of their accessibility.

dlev
  • 48,024
  • 5
  • 125
  • 132
  • Exactly. You can even run it at runtime from Java - using Reflection API. – zacheusz Jul 22 '11 at 19:44
  • dlev, agree with your answer, but i dont understand the point in defining main method as public in a default class. i also read that "Public - main method is called by JVM to run the method which is outside the scope of project therefore the access specifier has to be public to permit call from anywhere outside the application". so was just confused how can the public method "main" defined in a default class be accessible to JVM. – mazem Jul 23 '11 at 23:08