Re: Static Variables and JAR Files
On Mar 3, 3:23 pm, Mark Space <marksp...@sbc.global.net> wrote:
Jason Cavett wrote:
These JAR files (AnotherPackage and EvenAnotherPackage) are being read
in by a separate tool. When ExtendedClassA and ExtendedClassB are
used within the context of this tool, ObjectX is instantiated twice
and has two separate values. As far as I can tell, the tool runs
ExtendedClassA and ExtendedClassB within the same JVM, so I am unsure
of what is going on.
Obviously, when you make a new class via inheritance, it gets it's own
copy of the static variable. So there will be one static for the parent
class, and one for the child class. The static is a "class variable"
and since there are two classes (parent and child) there are two static
variables.
To clarify this since I think it could be misinterpreted:
If you try the following program:
class A {
static String var = "ClassA";
}
class B extends A {
}
public class Test {
public static void main(String[] args) {
B.var = "SetInProgram";
System.out.println("A.var is:"+A.var);
System.out.println("B.var is:"+B.var);
}
}
The output of this program
A.var is:SetInProgram
B.var is:SetInProgram
shows that there is only one field even though B extends A. I can add
a declaration to B:
class B extends A {
static String var = "ClassB";
}
Now when I run this I get:
A.var is:ClassA
B.var is:SetInProgram
The definition in B hides the one in A (or 'shadows' I'm never quite
sure of which terminology is used where) -- though a user could still
reference it as A.var.
So regardless of the number of times we extend a class, we declare
only a single instance of its static fields. However if the new class
does not hide the original field, we can use a new name for the field.
Regards,
Tom McGlynn