Image

Java - Core Java - Access Modifiers

Access Modifiers

The access modifier in java basically provide the scope and accessibility of data member like variable, method, constructor or class in java. according to our need and necessity or program requirement we can change the scope and accessibility of variable, method, constructor or class in java.

Java having four type of access modifiers

  • public
  • private
  • protected
  • default - no keyword required
  • 1. public

    The public access modifier is specified using the keyword public. The public access modifier has the widest scope among all other access modifiers. Classes, methods or data members which are declared as public are accessible from everywhere in the program. There is no restriction on the scope of public data members.

    2. private

    The private access modifier is specified using the keyword private. The methods or data members declared as private are accessible only within the class in which they are declared. Any other class of same package will not be able to access these members. Classes or interface cannot be declared as private.

    3. protected

    The protected access modifier is specified by using keyword protected. The methods or data members declared as protected are accessible within the same package or sub classes in different packages.

    4. default

    When no access modifier is specified for a class, method or data member – It is said to be having the default access modifier by default. The data members, class or member methods which are not declared using any access modifiers i.e. having default access modifier are accessible only within the same package