What are access modifiers in Java?
These are the modifiers which are used to restrict the visibility of a class or a field or a method or a constructor. Java supports 4 access modifiers.
1. public: The public access modifier is accessible everywhere. It has the widest scope among all other modifiers.
2. protected: The protected access modifier is accessible within the package and outside the package but through inheritance only. The protected access modifier can be applied to the data member, method and constructor. It can't be applied to the class.
3. default: If you don't use any modifier, it is treated as default by default. The default modifier is accessible only within the package. It cannot be accessed from outside the package.
4. private: The private access modifier is accessible only within the class. A class contains private data member and private method. If we are accessing these private members from outside the class, so there is compile time error. So we have to access them only within the class. If you make any class constructor private, you cannot create the instance of that class from outside the class. A class cannot be private or protected except nested class.
No comments:
Post a Comment