Access Modifiers in Java

Almost all our example contains public keyword. You may be familiar with it. But now, lets talk about it in detail. They are called Access Modifiers.

Scope or accessibility of any class, method, field or constructor is defined by access modifiers.

We can change the availability of our class, method, field or constructor by using these access modifiers.

Lets see the table below:

Access ModifierWithin ClassWithin PackageOutside Package (Subclass only) Everywhere
private
default
protected
public

  • private: This modifier lets us to access code within same class only.
  • default (or empty): This modifier lets us to access code within same package but any classes.
  • protected: This modifier lets us to access code within same package and subclass only.
  • public: This modifier lets us to access code from anywhere.

We will learn more of subclass and packages later.

So, up to now we have been using public keyword so that it will be accessible from anywhere.

We will be using these access modifiers in coming chapters.

Methods in Java Previous Next Objects in Java