24
class A {
    private int foo;
    void bar(B b) { b.foo = 42; }
}

class B extends A { }

This fails to compile with the error:

A.java:3: error: foo has private access in A
    void bar(B b) { b.foo = 42; }
                     ^
1 error

Adding a cast to the base class makes it work.

void bar(B b) { ((A) b).foo = 42; }

Can someone point me to an explanation about why the first snippet is illegal? What's the reason it's prohibited? Here's what the JLS says:

Otherwise, the member or constructor is declared private, and access is permitted if and only if it occurs within the body of the top level class (§7.6) that encloses the declaration of the member or constructor.

As best I can tell, my code meets this wording. So is this a bug with the Java compiler, or is my interpretation of the JLS incorrect?

(Note: I'm not looking for workarounds, like making the variable protected. I know how to work around this.)

1
  • 4
    @John Kugelman: Your statement "Why can't I access A.foo from a method of class A?" is not quite correct. Actually you are trying to access B.foo from a method of class A. But according to JLS §8,2 private members are not being inherited by the subclass B. JLS §6.6 says that accessing a member through a qualified name requires access control to be applied. So the compiler looks if the class member foo in B is accessible, but there is no such member in B. Nevertheless, it kindly tells you that your intended inheritance fails, because foo has private access in A.
    – MicSim
    Feb 10, 2015 at 19:20

7 Answers 7

16
+500

Error message "has a private access in A" is a java bug for a very very long time.

JDK 1.1:

JDK-4096353 : JLS 6.6.1: When subclass references are used to access privates of superclasses

contains code snippet exactly conforms the question one

class X{
  private static int i = 10;
  void f()     {
    Y oy = new  Y();
    oy.i = 5;  // Is this an error? Is i accessable through a reference to Y?
  }
}
class Y extends X {}

They tried to fix it and it leads to

JDK-4122297 : javac's error messages are not appropriate for a private field.

======TP1======
1  class C extends S {
2      void f(){
3          java.lang.System.out.println("foo");
4      }
5  }
6
7  class S {
8      private int java;
9  }
======
% javac C.java
C.java:3: Variable java in class S not accessible from class C.
    java.lang.System.out.println("foo");
    ^
C.java:3: Attempt to reference field lang in a int.
   java.lang.System.out.println("foo");
       ^
2 errors
======

But by specification java isn't inherited in C and this program should compile.

It fixed in 1.2, but appears in 1.3 again

JDK-4240480 : name00705.html: JLS6.3 private members should not be inherited from superclasses

JDK-4249653 : new javac assumes that private fields are inherited by a subclass

And when generics come

JDK-6246814 : Private member of type variable wrongly accesible

JDK-7022052 : Invalid compiler error on private method and generics


However, by the JLS this member simply doesn't exist in the inherited type.

JLS 8.2. Class Members

Members of a class that are declared private are not inherited by subclasses of that class.

So b.foo is illegal because class B has no field named foo. It is no restriction, it is an absent field in B.

Java has strong typing and we cannot access fields that do not exist in B even if they exist in superclass A.

Cast (A) b is legal because B is a subclass of A.

A has a field named foo and we can access this private field because b(B b) is a function in class A even if b != this due to

JLS 6.6.1. Determining Accessibility

Otherwise, if the member or constructor is declared private, then access is permitted if and only if it occurs within the body of the top level class (§7.6) that encloses the declaration of the member or constructor.

Also if we write

class A {
  private int foo;
  void baz(A b) { b.foo = 42; }
}

class B extends A { }

class T {
  void x() {
    B b = new B();
    b.baz(b);
  }
}

It will compile because Java infer type arguments for polymorphic calls.

JLS 15.12.2.7. Inferring Type Arguments Based on Actual Arguments:

A supertype constraint T :> X implies that the solution is one of supertypes of X. Given several such constraints on T, we can intersect the sets of supertypes implied by each of the constraints, since the type parameter must be a member of all of them. We can then choose the most specific type that is in the intersection

4
  • 2
    "So b.foo is illegal, because class B has no field named foo." -- Notice that the compiler error message is that foo is inaccessible, not that it doesn't exist. "...access is permitted if and only if it occurs within the body of the top level class (§7.6) that encloses the declaration of the member or constructor." -- As I see it, this condition is met by my code. Feb 9, 2015 at 19:23
  • 2
    Compiler behavior fits specification, but error message don't. Very interesting...
    – Nikolay
    Feb 9, 2015 at 19:29
  • 2
    The thing that was confusing to me is that an instance of B has a field foo but the type B does not, and the part of the JLS I quoted only applies to members of the type. Feb 10, 2015 at 22:46
  • It's all about inheritance. When you subclass type with private members you shouldn't care about your members and variables name collisions with it. Take a look at TP1 test in answer. And you can add new field foo to B type, for example. Instance of B in this case can have two independent fields foo, one in type A and one in type B.
    – Nikolay
    Feb 11, 2015 at 8:53
13

You can't say b.foo because foo is private and thus will not be inherited, as a result the B class can't see the foo variable and is not aware if a variable named foo even exist - unless its marked protected (as you said) or default (as they are in the same package i guess) or public.

If you want to use foo without using an explicit cast like your second example you must use this.foo or just foo which has an implicit this. As Javadocs specified, the this keyword main reason is to prevent that:

The most common reason for using the this keyword is because a field is shadowed by a method or constructor parameter.

When you used ((A) b) you are casting the reference type and the compiler will see it like if you are using an A reference variable type, in other words something like A a, and a.foo is completely legal.

An illustrated summary of visibility and access to superclass's private instance variables: here

13
  • 1
    I understand what the compiler is doing. I want to know if my use case is intentionally prohibited or if this is a flaw in the JLS or Java compiler. According to the JLS quote in @Alex's comment, it seems to me that my code meets the language spec. Feb 9, 2015 at 19:07
  • 1
    No, it's about private variables. "Otherwise, the member or constructor is declared private, and access is permitted if and only if it occurs within the body of the top level class (§7.6) that encloses the declaration of the member or constructor. " Feb 9, 2015 at 19:10
  • 1
    but how do you call variables in your classes ? have you ever called them without specifying a reference type ? if not then you are using the keyword this!
    – Tarik
    Feb 9, 2015 at 19:22
  • 3
    @JohnKugelman I think perhaps the error message is misleading you. The actual error should probably have been "foo cannot be resolved or is not a field" as it is for any field that does not exist in an object. Trying to look up a foo in a B is pointless. Only the compiler is trying to be friendly and tell you why there is no foo in B. Once you cast it, you have a value of type A, and that value most certainly has a foo variable as far as A is concerned. Feb 9, 2015 at 20:25
  • 2
    This answer should be the accepted answer. You can't access a private variable if you are a referencing it outside of the class. "Why won't this compile?" You cannot access a private variable outside of a class's type. "But I'm calling it from a subclass with the code inside the class with the private variable." You still can't access it because your subclass isn't a strong reference type of your super class. It's inherited. That's why typecasting works. docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
    – Luminous
    Feb 12, 2015 at 13:44
2

The specification for field access expressions, chapter 15.11 says:

If the identifier does not name an accessible member field in type T, then the field access is undefined and a compile-time error occurs.

From the perspective of super class, looking at the types, I'd argue that the member is not accessible, hence the error.

I think the case you're presenting is closer to accessing a member as a field, which is shown in example 15.11-1-1.

class S           { int x = 0; }
class T extends S { int x = 1; }
class Test1 {
    public static void main(String[] args) {
        T t = new T();
        System.out.println("t.x=" + t.x + when("t", t));
        S s = new S();
        System.out.println("s.x=" + s.x + when("s", s));
        s = t;
        System.out.println("s.x=" + s.x + when("s", s));
    }
    static String when(String name, Object t) {
        return " when " + name + " holds a "
                        + t.getClass() + " at run time.";
    }
}

Just to answer your question:

Kindly explain what sort of bad code the restriction is protecting against.

Please consider following snippet.

public class X {
    private int a;

    public void bar(Z z) {
        z.a // not visible, but if was, what 'a' 
            // would you actually access at this point 'X' or 'Z'
    }
}

public class Z extends X {
    private int a;
}
3
  • 1
    You're inside X and outside Z, your code should only see X's a.
    – fps
    Feb 9, 2015 at 20:15
  • 1
    @Magnamag, yes, but I would argue this way it works is consistent with static binding of accessing the field outside of X and Z, which makes it more intuitive (at least for me). Consider 15.11 of docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.11, and an example Example 15.11.1-1 - I mean just to point it out, you're just accessing a member of a variable, passed as an argument, which just happens to be of a type extending X, but not inheriting a, because of JSL 8.2.
    – lpiepiora
    Feb 9, 2015 at 22:21
  • 1
    Sure! Actually, code would be a mess if what the OP poses in his question was valid. My point was that the specification wasn't covering that 'strange' use case correctly. However, the link you provided clarifies the issue, specifically: " If the identifier does not name an accessible member field in type T, then the field access is undefined and a compile-time error occurs". You should add that link to your answer, as well as the quote and some argumentation.
    – fps
    Feb 9, 2015 at 23:05
1

It looks to me that the spec is inconsistent. As John states, the body of the spec states

Otherwise, the member or constructor is declared private, and access is permitted if and only if it occurs within the body of the top level class (§7.6) that encloses the declaration of the member or constructor.

and there is no mention of subclasses. So class A should compile correctly. However example 6.6-5 states

A private class member or constructor is accessible only within the body of the top level class (§7.6) that encloses the declaration of the member or constructor. It is not inherited by subclasses.

This second statement is both weaker (no only if), but brings subclasses to the table. According to this A should not compile.

0

Java is finicky about accessing private variables via a reference type that shouldn't have access to that variable. You should be able to do this legally by writing ((A) b).foo = 42.

1
  • 1
    I'm not sure there's going to be a good answer other than "the JLS says so," "the rules are simpler this way because you don't have to special-case 'well, if the field originally came from this class, it's okay...,'" or "only James Gosling can answer that." Feb 7, 2015 at 0:28
-1

We can't inherit the private fields or methods. So in your code Class B is completely unaware of variable foo even though you're accessing from its own class A.

1
  • 1
    This is already covered by other answers. Also, please cite your sources. Feb 10, 2015 at 13:35
-1

Isn't this what the default access modifier is for?

Try this :

public class blah{
    static class A {
        int foo;
        void bar(B b) {b.foo=42;}
    }
    static class B extends A {

    }
}

You cannot access the private member directly from an ancestor, that is what private means. Now why does it work when you cast? And does that mean the documentation is incorrect?

I mentioned to a colleague that the java documentation may be erroneous and he points out that you are actually setting the value of foo from inside class A. So everything is correct. You cannot (because it is private) access foo from an descendant, so you must cast. And you cannot do that outside of the body of A.

I believe this is the correct answer.

10
  • I'm not sure it is a workaround. The reason this problem has never been 'fixed' is because this is what the default access modifier is for.
    – Richard
    Feb 12, 2015 at 0:53
  • If you put the two classes in different packages you get the same problem: "foo is not public in A; cannot be accessed from outside package". Feb 12, 2015 at 0:57
  • That's correct? But default doesn't just mean 'package private'. It also deals with inheritance, which is why it works in this context. Can you explain a little more about what exactly you consider the problem to be?
    – Richard
    Feb 12, 2015 at 1:08
  • My question is about the code I wrote. Modifications are off the table. I think/thought it should compile, so my question is, "Why doesn't this compile?" Not, "How can I make it compile?" Feb 12, 2015 at 3:06
  • I think this is as designed. You can access the private member variables when you cast because you're on the object (just as you could with reflection). If you want a member variable accessible between classes but not to descendents, you put the friendly classes in the same package and use default. All descending classes are outside of that package. I think the thing about java access is that it's really a 'guideline' because nothing is truly private in Java, because of reflection.
    – Richard
    Feb 12, 2015 at 10:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.