Visiblity Modifiers and Scope
In Java, the data members and methods are encapsulated together within a class. Java uses certain reserved words called modifiers that specify the properties of the data, methods, and classes and how they can be used. Java classes, fields, constructors and methods can have one of four different access modifiers private, default, protected and public. The access to classes, constructors, methods and fields are regulated using access specifier or modifier. A class can control what information or data can be accessible by other classes. Depending upon the access level, access is restricted or allowed. The public access modifier means that all code can access the class, field, constructor or method, regardless of where the accessing code is located. Public access modifier is a least restrictive access modifier.
Private access modifier is the most restrictive access level. Methods, Variables and Constructors that are declared private can only be accessed within the declared class itself. The protected keyword deals with inheritance, which takes an existing class and adds new members to that class without touching the existing class. Protected variables and methods allow the class itself to access them, classes inside of the same package to access them, and subclasses of that class to access them.Classes in the same package can also access protected fields, methods and constructors as well, even if they are not a subclass of the protected member’s class.