我们如何在没有类名的情况下访问静态变量

kum*_*nny 1 java static

我们如何访问没有类名的静态变量?静态变量总是用类名限定,但在这种情况下,我可以在没有类名的情况下使用它。怎么可能?

    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.
    }


    }
Run Code Online (Sandbox Code Playgroud)

在创建学生对象后的下面程序中,变量已经加载到内存中,但我不能不使用对象引用直接访问它。但我们可以为静态做。

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


}
Run Code Online (Sandbox Code Playgroud)

Wil*_*sem 7

静态变量总是用类名限定

首先,您必须使用类名进行限定是不正确的,例如您可以使用静态导入:

import static java.lang.Math.PI;
Run Code Online (Sandbox Code Playgroud)

接下来您可以Math.PI简单地使用PI. 例如:

import static java.lang.Math.PI;

public class Foo {

    public static void main (String[] args) {
        System.out.println(PI);
    }

}
Run Code Online (Sandbox Code Playgroud)

可以在此处找到更多信息。

接下来只要你在类的范围内,所有静态成员都可以直接寻址,无需限定。换句话说,这个代码片段:

public class Foo {

    public static int static_member;

    //within this scope you can call static_member without Foo.

}
Run Code Online (Sandbox Code Playgroud)