2

I have code very much like the following.

package my.pkg;

public abstract class X {
    private CapableField field;

    public abstract void doSomething();

    public X(CapableField fieldValue) {
        this.field = fieldValue;
    }
}

And:

package my.pkg.sub;

public class Y extends my.pkg.X {
    public void doSomething() {
        this.field.doSomething();
    }
}

Why is this even legal code in Java? I thought "private" meant that the field will not be directly accessible in subclasses, and that this was a fairly basic tenet of class inheritance. Making X concrete instead of abstract changes nothing.

What do I do if I specifically want a field, or member function, to be accessible only inside the class where it is defined, and not in some random subclass of the defining class?

2
  • 4
    Can't be. You should have a compilation error! Are you sure that pasted code is what you actually compiled? Commented Feb 21, 2011 at 10:55
  • 1
    As others already noted, this is not legal in Java. private indeed means what you thought it means. What compiler / IDE you are using? Commented Feb 21, 2011 at 10:56

5 Answers 5

3

This is not true. Most likely you've actually definied Y as an inner class. This way the private fields of the outer class are indeed visible like that.

Sign up to request clarification or add additional context in comments.

1 Comment

No, they are separate classes with an inheritance relationship. However, as noted, that was not my problem.
2

Doesn't compile for me too! I suspect your Java implementation.

Comments

1

This is impossible. May be you missed something when you explain your question.

1 Comment

Indeed. Buried deep in the actual code for Y was private CapableField field;. Talk about stupid; when I took that out I got exactly the compilation errors I was expecting. PEBKAC, obviously.
0

private members are not visible in inheritance except in inner class scope. If you want them to be accessed by the subclass then declare them as protected. or use setters and getters.

and in your code you used package keyword in your package declaration which is not allowed and gives compilation error.

Comments

0

Make sure that your classes in two different files. for example X.java and Y.java and y not an inner class

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.