Java Fields Accessibility (and not Visibility!!!) / Public – Private – Protected ….


For a long time, my understanding of Java fields accessibility was wrong !!!

Here are the right accessibility for public, private, protected and package fields

private : can be accessed only from the class declaring the field

public : can be accessed from everywhere

package (when no visibility is specified) : can be accessed from every class within the same package

protected : can be accessed from any subclass OR from any class within the same package (protected = package + subclasses)

Advertisements

5 thoughts on “Java Fields Accessibility (and not Visibility!!!) / Public – Private – Protected ….

  1. That “protected” modifier is stupid. I only want to allow sub-classes to access a field of their parent class – not the whole package… I thought that “protected” does that, but it seems it is less restrictive…

    And by the way, why the heck would a subclass be in a different package (hence the difference between “package” and “protected”)!?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s