Java public private package visibility modifiers

Java public private package visibility modifiers. Basic encapsulation in Java.

So far when I created a class, method or an attribute, let's call them all together elements, I used public visibility. What does it mean? It means, that such element is visible from any other class in the whole application. You may think that it's a good thing, but not always. Generally some elements are local and should not be visible to everyone. For example attributes. It is really a bad thing to have publicly visible attributes. Why? Because you have absolutely no control over changing or getting their value.

In order to regain this control they can't be publicly visible. If they are not meant to be public, then they must be ... private. Private visibility is the opposite of public visibility. Private attribute is visible only in a class, where it's defined.

But usually you have to be able to access some elements from another classes. In order to get or set a value of an attribute, you must create a getter and setter, standardized methods, that have public visibility and can be used to get or set a value of an attribute.

You can easily create them using CONTROL + Space in Eclipse. In the next video, I'll show you how generate getters and setters in Eclipse more effectively.

But back to visibility modifiers. There are two other modifiers. If you omit visibility modifier, you set package visibility. Such element is accessible only from classes, that are in the same package.

And the last visibility modifier is protected, which is something between package and public visibility. Element with modifier protected is accessible from all classes, that are in the same package and from any subclass. Subclasses are part of class inheritance, which I'll present later.