Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

public static void main () access non static variable

Its said that non-static variables cannot be used in a static method.But public static void main does.How is that?

like image 921
user1526671 Avatar asked Jul 17 '12 12:07

user1526671


People also ask

Can I access non-static variable in static method?

In the static method, the method can only access only static data members and static methods of another class or same class but cannot access non-static methods and variables.

Can main access non-static variables?

Yes, the main method may access non-static variables, but only indirectly through actual instances.

How do you call a non-static method in public static void main?

Since you want to call a non-static method from main, you just need to create an object of that class consisting non-static method and then you will be able to call the method using objectname.


1 Answers

No, it doesn't.

public class A {
  int a = 2;
  public static void main(String[] args) {
    System.out.println(a); // won't compile!!
  }
}

but

public class A {
  static int a = 2;
  public static void main(String[] args) {
    System.out.println(a); // this works!
  }
}

or if you instantiate A

public class A {
  int a = 2;
  public static void main(String[] args) {
    A myA = new A();
    System.out.println(myA.a); // this works too!
  }
}

Also

public class A {
  public static void main(String[] args) {
    int a = 2;
    System.out.println(a); // this works too!
  }
}

will work, since a is a local variable here, and not an instance variable. A method local variable is always reachable during the execution of the method, regardless of if the method is static or not.

like image 98
Keppil Avatar answered Oct 13 '22 23:10

Keppil