We have already seen a brief introduction to ‘Java modifiers’ in the ‘Basic Java concepts‘ post. As we have already mentioned, there are four access modifiers in Java. They are:

  • public
  • private
  • protected
  • default

We will discuss whether classes, methods or variables can make use of the access modifier and their scope.

public’ access modifier:

The public access modifier is applicable to classes, methods and variables.

Any class, method and variable declared with the ‘public’ access modifier is visible to all outside the class or within the class.

The ‘public’s access modifier is the most liberal of all access modifiers.

private‘ access modifier:

The private access modifier is applicable to classes, methods and variables as well.

When we declare a class to be ‘private’ its variables and methods are visible only within the class. It is the most restricted of all access modifiers. If you do not want any class to access the methods and variables of a particular class, it is good to declare it as ‘private’.

Point to be noted: A top level class cannot be declared as ‘private’. Only inner classes and nested classes can be declared to be ‘private’.

‘default’ access modifier:

If a class, method or variable do not have an access modifier, it can safely be assumed that they have the ‘default’ access modifier.

The class, method and variable which have the ‘default’ modifier are only accessible to other classes, methods and variables in the same package.

Note: ‘default’ is not a keyword and is not used anywhere. The ‘default’ keyword is just assumed to be there.

protected‘ access modifier:

The protected access modifier is applicable to methods and variables only.

When a method or variable is declared as ‘protected’ it is only visible to those in the same package. In addition, the methods and variables are visible to those which are in a different package if they sub-class from the original class.

Come again tomorrow as I discuss ‘Exceptions’.

I’m participating in #BlogchatterA2Z by Blogchatter 

(Visited 113 times, 1 visits today)

Related Posts

3 thoughts on “Declaring Java modifiers

Leave a Reply