Understanding access modifiers

What are access modifiers ?

  • They define the ‘visibility’ of the properties and methods
  • They are similar to making your post on Facebook visible to either just yourself, or just your friends, or making it public
  • They¬†tell which properties and which methods can be accessed and which can’t based on what is trying to access them.

Types of Access Modifier :

In Java, there are 4 types of access modifiers

  1. Default: Visible to the package. the default. No modifiers are needed
  2. Private: Visible to the class only. It is like having a personal bike which only you use.
  3. Protected: Visible to the package and all the subclasses. It is like having a car which you and your family use.
  4. Public: Visible to the world. It is like a public bus which anyone can ride.

Example using access modifiers

 

Output:

C:UsersRachhek ShresthaDesktopjavaclassday3>java Student
The roll no. of Student is 12
The Phone no. of Student is 9841895794
The Phone no. of Student is 90
The marks of the Student is 90

Note:

  • Package: You can think a Package as a folder. A folder is a package. Every file inside a folder is inside its package.

Leave a Comment

Your email address will not be published. Required fields are marked *