New Delhi, India
minigranth@gmail.com

Access Modifiers In Java

Created with Sketch.

Core Java Tutorial

[fblike]

Access Modifiers in Java : Introduction

  • Before discussing encapsulation let us learn about access modifiers in Java.
  • Access modifiers set the access and scope of members of classes, within or outside classes and packages.
  • Java provides with four access modifiers which can be used according to the need and logic. These are :

 

This image describes the types of access modifiers in java.

Access Modifiers : Types

 

Access Modifiers In Java : Private Access

  • Fields, methods and constructors declared private are available only within the class in which they are declared. Any external object can’t access private members of a class.
  • If a class has all members private then it is called encapsulated class. We will discuss it later.
  • Private fields can only be accessed by public methods.
  • Private access has the least scope and is most restrictive.

Access Modifiers In Java : Public Access

  • Fields, methods and constructors declare public are available anywhere within or outside classes, are also available in other classes and also within and outside packages.
  • Public members can be accessed using external object.
  • Public access has the widest scope and is least restrictive.

Access Modifiers In Java : Protected Access

  • Protected access lies between that of public and private. Protected access cannot be applied to class and interfaces. It can applied only to fields, methods and constructors.
  • Fields, methods and constructor declared protected can only be accessed by its subclass within or outside package. Hence protected members are only accessible within or outside package in subclass.

Access Modifiers In Java : Default Access

  • If no access modifier is specified then default specifier is used automatically.
  • Default has scope only within the package.