Prathamesh, There is only one A variable no matter how many instances or subclasses you have. While all of those references do refer to the same A variable, the code is harder to read. It is better to always refer to the static variable through the class hosting it - in this case X. Otherwise, someone reading the code has to figure out that there are three different ways of referring to the same variable in the method.
Originally posted by Prathamesh Gaddam: How does the static memeber variable behaves towards inheritance?
Until a subclass hides it, a static field or method is available through the class itself, its subclasses and instances of all those classes. However, it is also available through null references! All that matters for those is the class the reference is declared as:
Although x is null, it is declared as being of class X, so x.A actually executes X.A.
That code also shows something that has been allowed in previous versions of Java: although the array index is invalid, Java 1.3 (I believe) allowed it and would print 5 - since only the declared type (X) was used. This is no longer possible though.
Now, if a subclass of X called Y would also declare a static field called A, then the declared type is what matters:
Amazing! It's what I call it as real fundu! Dhanyavaad (Thank you in Hindi).
Please confirm as what I have understood.
In the hierarchy of class and its sub-class a single copy of static variable is maintained on heap which can be referred by null or class-type reference.
Peter Chase
Ranch Hand
Joined: Oct 30, 2001
Posts: 1970
posted
0
While it is legal Java to invoke a static method using an object reference (which may be null), it is very bad practice to do so. You should always invoke it using the class literal.
Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.<br /> <br />#:^P
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to
run our stuff on 16 servers instead of 3.