Visible to the package. theThe default. No modifiers are needed.
Visible to the class only (private).
Visible to the world (public).
Visible to the package and all subclasses (protected).
Variables and methods can be declared without any modifiers that isare called. Default examples:
String name="john";name = "john"; public int age(){ return age; } Private Access Modifieraccess modifier - private: Methods
Methods, Variablesvariables and Constructorsconstructors that are declared private can only be accessed within the declared class itself.Private The private access modifier is the most restrictive access level. Class and interfaces cannot be private.
Variables that are declared private can be accessed outside the class if public getter methods are present in the class.
Using the private modifier is the main way that an object encapsulates itself and hidehides data from the outside world. examples
Examples:
Public class Details{ private String name; public void setName(String n){ this.name=n;name = n; } public String getName(){ return this.name; } } Public Access Modifieraccess modifier - public: A
A class, method, constructor, interface, etc. declared public can be accessed from any other class. Therefore fields, methods, blocks declared inside a public class can be accessed from any class belonging to the Java Universeuniverse.
However, if the public class we are trying to access is in a different package, then the public class still need to be imported.
Because of class inheritance, all public methods and variables of a class are inherited by its subclasses. example
Example:
public void cal(){ } Protected Access Modifieraccess modifier - protected: Variables
Variables, methods and constructors which are declared protected in a superclass can be accessed only by the subclasses in otheranother package or any class within the package of the protected members' class.
The protected access modifier cannot be applied to class and interfaces. Methods, fields can be declared protected, however methods and fields in a interface cannot be declared protected.
Protected access gives the subclass a chance to use the helper method or variable, while preventing a nonrelated class from trying to use it.
class Van{ protected boolean speed(){ } } class Car{ boolean speed(){ } }