views:

659

answers:

3

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.

+10  A: 

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
correct [to complete 10 characters]
Adeel Ansari
+1  A: 

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.

romaintaz
Protected has package access, see the other responses here as well as the link.
Eek
@Eek> Indeed, so I edited my post
romaintaz
+2  A: 

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
Could be in JDK7 modules...
Tom Hawtin - tackline
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