Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing non-static members through the main method in Java

Tags:

java

As a rule in object-oriented paradigm, a static method can have access only to static variables and static methods. If it is so, an obvious question arises as to how can the main() method in Java has access to non-static members (variables or methods) even though it is specifically public static void...!!!

like image 756
Bhavesh Avatar asked Oct 25 '11 18:10

Bhavesh


Video Answer


1 Answers

The main method does not have access to non-static members either.

public class Snippet
{
   private String instanceVariable;
   private static String staticVariable;

   public String instanceMethod()
   {
      return "instance";
   }

   public static String staticMethod()
   {
      return "static";
   }

   public static void main(String[] args)
   {
      System.out.println(staticVariable); // ok
      System.out.println(Snippet.staticMethod()); // ok

      System.out.println(new Snippet().instanceMethod()); // ok
      System.out.println(new Snippet().instanceVariable); // ok

      System.out.println(Snippet.instanceMethod()); // wrong
      System.out.println(instanceVariable);         // wrong 
   }
}
like image 123
tjg184 Avatar answered Sep 30 '22 19:09

tjg184