Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can we access static variable without class name

Tags:

java

static

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);
}


}
like image 840
kumar Anny Avatar asked Mar 26 '26 16:03

kumar Anny


1 Answers

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.

}
like image 94
Willem Van Onsem Avatar answered Mar 28 '26 06:03

Willem Van Onsem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!