class A{
void display(){
System.out.println("hai");
}
}
class B {
static A a;
}
class C{
public static void main(String args[])
{
B.a.display();
// no compile- time error here.why?
}
}
Also I know that a will be set to null during runtime. But shouldnt the compiler know that we are accessing a non-static method via a static reference variable? This gives a null pointer exception when executed but why is the compiler not giving an error.
Does this mean a static reference variable behaves exactly like an object reference and thus can invoke any method(static and non-static) of the class?
Edit: I am basically confused with static field's access rules. By definition static fields can only directly access other static fields. So does this not include "invoking" a method using a static reference variable? And display() is accessed before its object is created. Is this valid?
1 Answer 1
"You keep using that word. I do not think it means what you think it means."
The static A a; in your code says, "a is a (reference to) an object of type A that is shared across all instances of class B. a is uninitialized.".
The compiler will have no context to determine when you are going to call the static main() method of class C, so it can't tell what the state of variable a will be at the time you call C.main();. In fact, you could just as easily have a class D:
class D
{
public static void main( String args[] )
{
B.a = new A();
C.main( args );
}
}
which would make the code above completely valid and runnable.
areferences an instance ofA, why shouldn't you be able to call an instance method?