1

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
}
}
3
  • 1
    The fact that the compiler doesn't suggest this auto completion doesn't mean you can't do it. It means you probably shouldn't do it. Commented Jul 11, 2017 at 10:14
  • 1
    You mean your IDE does not provide it as an auto-complete option. Has nothing to do with the compiler. It will compile and execute without throwing a NullPointerException. Commented Jul 11, 2017 at 10:15
  • 1
    should work perfectly fine without any compilation error.Looks like an IDE issue.Eclipse do not create any such problem Commented Jul 11, 2017 at 10:22

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.