Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 778
chillysapien Avatar asked Jan 21 '09 10:01

chillysapien


2 Answers

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.

like image 187
Sven Lilienthal Avatar answered Sep 29 '22 14:09

Sven Lilienthal


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.

like image 32
Romain Linsolas Avatar answered Sep 29 '22 16:09

Romain Linsolas