如何在没有类名的情况下访问静态变量?静态变量始终使用类名限定,但在这种情况下,我可以使用它而不使用类名。怎么可能?
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.
}
}
在创建学生对象后的下面的程序中,变量已经加载到内存中,但我无法使用对象引用直接访问它。但我们可以为静态做。
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);
}
}
静态变量始终使用类名限定
首先,你不得不使用类名来限定,你可以使用静态导入例如:
import static java.lang.Math.PI;
接下来,您只需使用Math.PI
即可参考PI
。例如:
import static java.lang.Math.PI;
public class Foo {
public static void main (String[] args) {
System.out.println(PI);
}
}
更多信息可以在here找到。
接下来,只要您在班级范围内,所有静态成员都可以直接进行处理,而无需符合条件。换句话说,这段代码片段:
public class Foo {
public static int static_member;
//within this scope you can call static_member without Foo.
}
只有当你从课堂外提起ClassName.staticMemberName
时才需要提供System.out.println(st.email);
。
在您的情况下,您在类中引用静态成员。
回答你的第二个问题:
非静态成员不能直接在静态方法中使用。它应该有对象参考。
所以,你的陈述应该是这样的
public class Student {
public static final String SCHOOL ="Harvard";
public static void main(String[] args) {
System.out.println(SCHOOL);
}
}
这是有效的,因为你在学生班级内,所以它是隐含的
public class Teacher {
public static final String SCHOOL ="Harvard";
}
public class Student {
public static final String SCHOOL ="MIT";
public static void main(String[] args) {
System.out.println(SCHOOL);
System.out.println(Teacher.SCHOOL);
}
}
输出:哈佛
public class Teacher {
public static final String SCHOOL ="Harvard";
public String Email = "[email protected]";
}
public class Student {
public static final String SCHOOL ="MIT";
public String Email = "[email protected]";
public static void main(String[] args) {
System.out.println(SCHOOL);
System.out.println(Teacher.SCHOOL);
Student student = new Student ();
System.out.println(student .Email);
Teacher teacher = new Teacher();
System.out.println(teacher.Email);
}
}
输出:麻省理工学院
输出:哈佛
这也说明了为什么这项工作,因为现在我们可以打印一个既有学校财产的老师和学生。
问题的第二部分:
您无法直接呼叫电子邮件,因为您的Main方法是静态的。因此,您不仅需要创建新的学生对象,还要使用它。
public class Student {
public static void someStatic() {
}
public static void otherStatic() {
someStatic(); //works
}
}
输出:麻省理工学院
输出:哈佛
您可以调用静态方法,而无需在您所在的同一个类中引用该类,或者通过使用静态导入。
import static Student.*;
public class OtherClass {
public static void other() {
someStatic(); //calls someStatic in Student
}
}
也:
qazxswpoi