Modifiers

Modifiers are keywords in Java that are used to change the meaning of a variable or method. In Java, modifiers are categorized into two types:
1. Access Modifiers
2. Non Access Modifiers

Access Modifiers

Access modifiers can be used to define access control for classes, methods and variables.

Types of Access Modifiers

  • public
  • private
  • default
  • protected

public: access modifiers is accessible everywhere. Example –
for class: public class Sample { }
for methods: public int add(a+b);
for variables: public int a;

private: access modifiers is accessible only within the class. Example –
private int a = 100;

default: if we don’t specify any modifier then it is treated as default. Example –
class Sample { }

protected: The protected access modifier is accessible only within package and outside of package through Inheritance. Example –
protected class Sample { }

ModifierWithin ClassWithin
Package
Outside of the package
(through Inheritance)
Outside of the
package
privateYesNo No No
defaultYesYesNoNo
protectedYesYesYesNo
publicYesYesYesYes
Access Modifier Table

Non Access Modifiers

Non-access modifiers do not change the accessibility of variables and methods, but they do provide them special properties.

Types of Non Access Modifiers

  • static
  • final
  • abstract
  • synchronized
  • Volatile

static: modifier is used to create class variable and class methods which can be accessed without instance of a class.

final: modifier for finalizing class, methods and variable i.e. it prevents its content from being modified. Final field must be initialized when it is declared. Example –
final int a = 100;

abstract: modifier is used to create abstract classes and abstract methods.

synchronized and volatile modifiers, which are used for threads.

Next

Leave a comment

Design a site like this with WordPress.com
Get started