Search code examples
javastatic-methodsstatic-variables

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

Solution

  • It's just your IDE. You could use emp.getBankVaultValue() there, and it would work. 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. 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; 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.)

    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, e.g.:

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

    The other (emp.getBankVaultValue()) works, but it's a quirk of syntax.