What’s the Difference Between Public, Default, Protected and Private Members in Java

What’s the Difference Between Public, Default, Protected and Private Members in Java

Access modifiers are special keywords that define the accessibility or scope of a member. We can specify how other code can interact with specific methods or variables within or outside classes and packages. Like many programming concepts, access modifiers are simple in practice but can seem confusing at first. Once you understand them, they can help make your code more readable and maintainable.

Understand the Difference Between Members

Java provides 4 types of access modifiers with different scopes and visibility. Any member without any specifier is dealt with as “Default” or “package-private”.

  1. Private: A private member is accessible only in the same class
  2. Default (package-private): A member without any access modifiers is known as default or package private. Which is accessible in all classes of the same package
  3. Protected: A protected member is accessing all classes of the same package and subclasses of the other packages.
  4. Public: A public member is accessible all classes of all packages

See the below graphical representation, which will help you better outstanding about the scope of all members in different cases.

What is Access Modifiers in Java
Access Modifiers and Their Scope in Java

Hope this tutorial helped to under the difference between private, package-private (default), protected, and public members. Please put your valuable suggestions in the comment box.

The post What’s the Difference Between Public, Default, Protected and Private Members in Java appeared first on TecAdmin.

General Articles TecAdmin