6

I realise that this is a very basic question, but it is one which has always bothered me. As I understand things, if you declare a field private in Java then it is not visible outside of that class. If it is protected then it is available to inherited classes and anything in the same package (correct me if either of those definitions is incorrect).

Does this mean it is not possible to declare a field that is accessible to only inherited classes and not other non-inherited classes in the same package?

I appreciate that there are ways around this, but are there instances when you would want to have this sort of behaviour?

Obviously the above question applies to methods as well as fields.

Many thanks.

Luc Touraille
  • 79,925
  • 15
  • 92
  • 137
chillysapien
  • 2,256
  • 1
  • 26
  • 42
  • Just a remark about vocabulary: what you're talking about here is *accessibility* of variables (or visibility). The scope of a variable is the part of the code where the variable can be used (for example, the scope of a local variable is the body of the method, or the block it's defined in). – Luc Touraille Jan 21 '09 at 14:11

3 Answers3

12

See: http://java.sun.com/docs/books/tutorial/java/javaOO/accesscontrol.html
Package > Subclasses, you can never have a field only visible by subclasses but not by classes from the same package.

Sven Lilienthal
  • 6,396
  • 4
  • 29
  • 25
4

Basically:

  • private: Accessible only by the class.
  • public: Accessible by any class.
  • protected: Accessible by the class, all inherited classes and the classes of the current package (edited).
  • no scope defined: Accessible by all classes of the current package.

more information here.

Romain Linsolas
  • 79,475
  • 49
  • 202
  • 273
  • Protected has package access, see the other responses here as well as the link. – Eek Jan 21 '09 at 11:11
2

Yes, Java's protected access is a little bit odd in that way. I can't immediately see why it's desirable at all. Personally it doesn't bother me for fields as I don't like non-private fields anyway (other than constants) but the same is true for other members.

.NET doesn't have the concept of package/namespace access visibility at all, but it has an alternative which is assembly (think "jar file" - not exactly the same, but close). Frankly I'd like to have namespace and deployment-unit visibility options, but it seems I'm doomed to disappointment...

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • But then there's still the issue of package level access to protected... so yes, modules will help, but it's still not ideal :( (I also prefer the "nested has access to outer privates" C# concept to the reverse in Java.) – Jon Skeet Jan 21 '09 at 14:45