I was fooling around with static members, I got confused when something compiled that I didn’t think should:
class ClassA {
static String s = " ";
}
public class ClassB extends ClassA {
private ClassB() {
s = "I feel like this shouldn't be possible.";
}
public static void main (String[] args) {
new ClassB();
System.out.println(s);
}
}
I don’t understand how ClassB can access the static member on ClassA. My understanding was that static information is kept with the class it’s declared on, and isn’t passed down into subclasses. Is that an incorrect assumption, or is the compiler doing something sneaky?
Not specifying an access modifier makes a member available to the whole
package. Statics are class-scoped, but that doesn’t mean you can’t access them from the outside.If you’d make it
private, you wouldn’t be able to access it.