πŸͺ” ΰ€Άΰ₯ΰ€­ ΰ€¨ΰ€΅ΰ€°ΰ€Ύΰ€€ΰ₯ΰ€°ΰ€Ώ!    Use Code: FESTIVALOFF300    Invoke the power of knowledge – Get β‚Ή300 to β‚Ή800 OFF on Java Courses 🎊
Celebrate & Learn πŸ™

Access-Modifiers in Java  


Introduction
  • Access modifiers are the keywords used to set access levels (visibility) for classes, methods, variables and constructors.
  • They help in implementing encapsulation and maintaining security in object-oriented programming.
  • Java provides four types of access modifiers:
    1. public
    2. protected
    3. default (no modifier)
    4. private
  • Why Use Access Modifiers?
    • To hide internal implementation details (data hiding).
    • To control access to class members from outside the class or package.
    • To follow the principles of encapsulation and object-oriented design.
    • To protect sensitive data and ensure modularity in large applications.

Types of Access Modifiers:-
  1. public:
    • The member is accessible from anywhere in the program.
    • Can be used across packages and classes.
  2. protected:
    • The member is accessible within the same package and also in subclasses (even if they are in different packages).
    • Cannot be accessed by non-subclass classes outside the package.
  3. default (no modifier):
    • The member is accessible only within the same package.
    • Cannot be accessed from classes in different packages.
  4. private:
    • The member is accessible only within the same class.
    • Cannot be accessed from outside the class, even by subclasses.
Access Control Table
Access Modifier Same Class Same Package Subclass (Other Package) Other Package
public βœ… βœ… βœ… βœ…
protected βœ… βœ… βœ… ❌
default βœ… βœ… ❌ ❌
private βœ… ❌ ❌ ❌
Java Program Example:
  • public class Car
    {
        private String model;
        protected int speed;
        public void startEngine()
        {
            System.out.println("Engine started");
        }
    }