How can we access static variable without class name? Static variable are always qualified with class name but in this case i am able to use it without class name. how its possible??
class Student
{
String email;
String name;
long phone;
static String school="jlc";
public static void main(String[] args)
{
Student st= null;
System.out.println(school);//this should be Student.school but its working.
}
}
In below programme after creating student object, variables are already loaded into memory, but i cannot directly access it with out using object reference.but we can do for static.
class Student
{
String email;
String name;
long phone;
static String school="jlc";
public static void main(String[] args)
{
Student st= new Student();
System.out.println(email);
}
}
Static variable are always qualified with class name
First of all, it is not true you have to qualify with a class name, you can use a static import for instance:
import static java.lang.Math.PI;
Next you can refer to Math.PI simply by using PI. For example:
import static java.lang.Math.PI;
public class Foo {
public static void main (String[] args) {
System.out.println(PI);
}
}
More information can be found here.
Next as long as you are in the scope of the class, all static members can directly be addressed without having to qualify. In other words this code fragment:
public class Foo {
public static int static_member;
//within this scope you can call static_member without Foo.
}
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