Its said that non-static variables cannot be used in a static method.But public static void main does.How is that?
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.
Yes, the main method may access non-static variables, but only indirectly through actual instances.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With