chillysapien
chillysapien

Reputation: 2316

Access levels of java class members

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.

Upvotes: 6

Views: 8037

Answers (3)

Romain Linsolas
Romain Linsolas

Reputation: 81647

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.

Upvotes: 4

Jon Skeet
Jon Skeet

Reputation: 1502806

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...

Upvotes: 2

Sven Lilienthal
Sven Lilienthal

Reputation: 6504

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.

Upvotes: 12

Related Questions