Access modifiers

In java, there are 4 types of access modifiers which are as follows.

  1. Public
  2. Private
  3. default
  4. protected

We check their accessibility at 4 levels which are.

  1. Class level
  2. Subclass level
  3. Its own Package level
  4. To all the packages or world

Let’s understand their accessibility in a  table form first, then we will discuss them.

Access modifiers

1. Default Access modifier: 

If you don’t use any modifier , it is considered as default. It is accessible only in its class and package.

Example of default access modifier: We have created 2 packages com.testingpool.demo  and com.testingpool.demo2. First package has a class called AddNumber which does not have any modifier i.e. it is having default access modifier.

We are trying to create its instance into another package, where it gives compile time error. Look at the example below for understanding.

2. private access modifier: 

Private access modifier is accessible only in the class.

Example of private access modifier: We have a class called Sample  which is having private data-member and method. If we try to access it into another class, it throws compile time error.

3. Protected access modifier: 

protected access modifier are accessible in its own package, but if you want to access it outside the package you have to access them using inheritance.

These can be applied to data-member, method ,constructor but not to the classes.

Example of protected access modifier without inheritance:

We have 2 packages com.testingpool.demo and com.testingpool.demo2.In first package, we have a class called AddNumber and a method displayName() which is having protected access modifier.

Now if, we try to access the method displayName(), it throws compile time error and suggest to change the visibility of the method to public.

This problem can be resolved by using inheritance.We will extend the class AddNumber to SubNumber.

4. public access modifier:

It has the visibility to the world, that means it can be accessed anywhere i.e. in its package,outside package,in all classes.

It can be applied to variables, methods, constructor and classes.


Note: A class cannot be private or protected except nested class.

 

Ask Question
If you have any question, you can go to menu ‘Features -> Q&A forum-> Ask Question’.Select the desired category and post your question.
Object class in java
this keyword
Shekhar Sharma

Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. He is an automation engineer having more than 8 years of experience who loves troubleshooting in automation and finding innovative ways to solve the problems. His other leisurely activities includes playing harmonica, paintings, sketching portrait, watching movies and travelling etc.

You may also like...

Leave a Reply

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