简体   繁体   English

无法通过Java中的引用变量访问静态方法

[英]Static method is not accessible through a reference variable in java

I am just trying to see if I can access static variable through a ´static´ method using a ´reference variable´ that is initialized to ´null´ (I know this is not recommended). 我只是想看看我是否可以使用初始化为“ null”的“引用变量”通过“ static”方法访问静态变量(我不建议这样做)。 But I can't seem to be able to access the method at all. 但是我似乎根本无法访问该方法。 Can't seem to spot what is wrong. 似乎无法发现问题所在。

class Emp {

 static int bank_vault;

 static int getBankVaultValue(){
    return bank_vault;
 }
}

public class Office {

public static void main(String[] args)
{
    Emp emp = null;

    System.out.println(emp.); // Here I don't get getBankVaultValue method option
}
}

It's just your IDE. 这只是您的IDE。 You could use emp.getBankVaultValue() there, and it would work. 您可以在emp.getBankVaultValue()使用emp.getBankVaultValue() ,它将起作用。 You can access the static method via that instance reference (even though it's null ; it's never dereferenced, since getBankVaultValue is static) and the static method can, of course, access the static variable. 您可以通过该实例引用访问静态方法(即使它为null ,也不会取消引用,因为getBankVaultValue是静态的),并且该静态方法当然可以访问静态变量。 But your IDE isn't offering you that suggestion because, as you said, it's a bad idea to access static members via an instance reference; 但是您的IDE并没有为您提供建议,因为正如您所说,通过实例引用访问静态成员是个坏主意。 to anyone looking at the code, it looks like you're accessing an instance member. 对于任何查看代码的人来说,似乎您正在访问实例成员。 (At least, I presume that's why the IDE isn't doing it.) (至少,我认为这就是IDE不这样做的原因。)

You're clearly aware it's a bad idea and you know how to do it properly, but for anyone else coming to the question/answers, the correct way to access that would be via the class name, eg: 您清楚地知道这是一个坏主意,并且知道如何正确地进行操作,但是对于任何其他提出问题的人,通过类名进行访问的正确方法是,例如:

System.out.println(Emp.getBankVaultValue());

The other ( emp.getBankVaultValue() ) works , but it's a quirk of syntax. 另一个( emp.getBankVaultValue()有效 ,但这是语法上的怪癖。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM