jonny five
jonny five

Reputation: 27610

What are the rules for subclassing accessing static members?

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?

Upvotes: 0

Views: 1215

Answers (3)

lsoliveira
lsoliveira

Reputation: 4640

Static information is absolutely not kept in the class it is declared on. Standard access control rules apply to every static member defined for a class. This means you can apply the private, protected, package protected (your case) and public access control modifiers to all static members of class (this includes methods).

See what the JLS has to say about access control: http://java.sun.com/docs/books/jls/third_edition/html/names.html#104285

Upvotes: 3

Maxim Zabolotskikh
Maxim Zabolotskikh

Reputation: 3367

In class B you actually set s on ClassA, not its instance. The line in your constructor is equivalen to

private ClassB() { 
         ClassA.s = "I feel like this shouldn't be possible."; 
    }

You can however omit "ClassA" because you access it from derived class.

Upvotes: 0

Luchian Grigore
Luchian Grigore

Reputation: 258638

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.

Upvotes: 4

Related Questions