i

JAVA Complete Course

Access Protection

In previous chapters we have already mentioned access modifiers in Java. Let’s revisit them shortly again. We have 4 different access modifiers:

Default – this is not written explicitly but if we don’t define any access modifier for our method or variables, it is default. Fields and methods with default access level, can be accessed from any class inside same package.

Private – Variables and methods with private access modifier are visible only inside the class in which they are defined

Protected – Variables and methods with protected access modifier are working like with default access level and additionally they are visible in their subclasses.

Public – public methods and variables are visible from any point of application.

In Java, encapsulation recommends us not to have variables public. Instead we should use private modifiers and access our variables with getter/setter methods. In other words, we should provide our users to access and modify our variables with methods and not directly.