Access Modifiers in Java

Posted on

An access modifier determine whether other classes can use a particular field or invoke a particular method. There are four access modifiers available in java.

  • public: ‘public’ members of class are accessible everywhere outside the class.
  • protected: ‘protected’ members of a class are accessible outside the class but within the package and outside the package through inheritance.
  • default: if programmer has not specified any modifiers, it is treated as ‘default’ access modifiers. The default access modifiers are accessible only within the package.
  • private: ‘private’ members of class are not accessible anywhere outside the class. They are accessible only within the class by the method of that class.

The following table shows the access to members permitted by each modifier.

Access Levels

Modifier

Class

Package

Subclass

World

public

Y

Y

Y

Y

protected

Y

Y

Y

N

default

Y

Y

N

N

private

Y

N

N

N

Question: Can you declare a class as private?

Answer: No, if we declare a class as a private then it is not available to java compiler and hence compile time error occurs. But, inner classes can be declared as private.

 

Example: public access modifier

Output:

 

Example: protected access modifier
The protected access modifier can be applied on the data member, method and constructor. It can’t be applied on the class.

Now, using inheritance, AccessModifierDemo class can access the method of the AccessModifier class which is in different package.

Output:
Hello World!

 

Example: default access modifier

Using inheritance

If we will create the AccessModifierDemo class within the “package com.c2s.java;” package, it will access the print method from other class.

 

Example: private access modifier

 

Stay tuned for more updates!

Leave a Reply

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

Time limit is exhausted. Please reload CAPTCHA.