Modifier in java

Visibility Modifier

  • Default : By defualt the class, data fields or variables and methods can accessed by any other class from the same package.
  • Public :  class, data fields and methods are accessible to any class in any package
  • Private : data fields and methods are accessible within declaring class
  • Protected : A protected data or a protected method in a public class can be accessed by any class in the same package or its subclasses, even if the subclasses are in a different package.
Access Modifier

Access Modifier

visibility modifier

Visibility Modifier Example

Static Modifier :

Declaring property (methods or data fields) as a static,  allows to share the property with all instances of the class. Further details are discussed in my previous article “Instance and Static variables and Methods.”

Final Modifier :

final keyword can be used with class, data fields or variables and methods.

  • Using final with class, it can’t be extended
  • Using final with method, it can’t be overrident by any subclass
  • Using final with variable or data field, it is a constant

Note :

  • If you are designing a class from user point of view then make all data fields private and accessor methods public
  • if you are designing a class from extender point of view then make all data fields and methods protected
  • Get and set methods are used to read and change private properties or data fields.
  • To protect data and hide internal details, use private modifier

Comments

  1. Reply

  2. Reply

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.