Access Modifiers in Java

May 13, 2018

Access modifiers control the access to classes, objects or variables, and methods within a project.

Types of access Modifiers –

  • Public
  • Private
  • Protected
  • Default. (No keyword is used)

Classes can have only two types – Public or Default.

Variables and Methods can be accessed outside a class either via inheritance or by creating an instance of the class where they belong to. They can have all four level of access modifiers.

Public variables and methods can be accessed anywhere and everywhere by both means (via inheritance or by creating an instance) within a project.

Private variables and methods can only be accessed within the same class. The cannot be accessed outside a class at all.

Protected and Default have the same level of protection with only one difference. Both can be accessed anywhere by both means (via inheritance or by creating an instance) within a package, but outside a package, only protected methods can be accessed via Inheritance and not by creating an instance of a class.

Public classes can be accessed anywhere in a project whereas a default class can only be accessed within the same package.

PS: For any questions, queries, and feedback, feel free to write us at saurabh@qatechhub.com or support@qatechhub.com. Happy Learning 🙂

 

Saurabh

About the Author

Saurabh

Follow Saurabh:

Leave a Comment: