Unlock the complete
Logicmojo experience for FREE

1 Million +

Strong Tech Community

500 +

Questions to Practice

50 +

Jobs Referrals

Access Modifiers in OOPs

Back to home
Logicmojo - Updated Dec 12, 2023



What are access Modifiers?

In object-oriented languages, access modifiers (or access specifiers) are keywords that control the accessibility of classes, methods, and other members. Access modifiers are a type of programming language syntax that makes it easier to encapsulate components.

There are just three access modifiers in C++. The number of them is increased to six in C#, whereas Java has four access modifiers but only three keywords for this purpose. The package-private modifier is used by default in Java when there is no keyword preceding it.

When a class is made public, it is accessible to both other classes in the same package and those from other packages. This is the most widely used class specifier. A class, on the other hand, cannot be designated private. The default access limitations will be imposed if no access specifier is specified. Other classes in the same package will have access to the class, but classes outside the package will not. When we say a class is inaccessible, we simply mean that we can't make an object from it or declare a variable of that kind. The protected access specifier can't be used on a class, either.

C++ uses the three modifiers called public, protected, and private.[3] C# has the modifiers public, protected ,internal, private, protected internal, and private protected. Java has public, package, protected, and private; package is the default, used if no other access modifier keyword is specified. The meaning of these modifiers may differ from one language to another. A comparison of the keywords, ordered from the most restrictive to the most open, and their meaning in these three languages follows. Their visibility ranges from the same class to the package where the class is defined to a general access permission. Below, the maximal access is written into the table.

Types of access Modifiers in Java

The access modifiers in Java specifies the accessibility or scope of a field, method, constructor, or class. We can change the access level of fields, constructors, methods, and class by applying the access modifier on it.

There are four types of Java access modifiers:

  1. 1. Private: A private modifier's access level is limited to the class. It isn't accessible outside of the class.

  2. 2. Default: A default modifier's access level is limited to the package. It's not possible to get to it from outside the package. If you don't indicate an access level, the default will be used.

  3. 3. Protected: A protected modifier's access level is both within the package and outside the package via a child class. The child class cannot be accessed from outside the package unless it is created.

  4. 4. Public: A public modifier's access level is visible everywhere. It can be accessible from within and outside the class, from within and outside the package, and from within and outside the package.

1. Private

Only members of the class have access to the private access modifier.

Example

We've built two classes in this example: A and Simple. Private data members and private methods are found in a class. There is a compile-time problem since we are accessing these secret members from outside the class.


class A{  
    private int data=40;  
    private void msg()
    {
        System.out.println("Hello java");
    }  
}  
public class Simple{  
    public static void main(String args[]){  
        A obj=new A();  
        System.out.println(obj.data);//Compile Time Error  
        obj.msg();//Compile Time Error  
   }  
}  

2. Default

If you don't specify a modifier, it will be treated as default. The default modifier is only available within the package. It's not possible to get to it from outside the package. It allows for more accessibility than a private setting. It is, nevertheless, more limited than protected and open.

Example

//save by A.java  
package pack;  
class A{  
  void msg()
  {
      System.out.println("Hello");
  }  
}  

//save by B.java  
package mypack;  
import pack.*;  
class B{  
  public static void main(String args[]){  
   A obj = new A();//Compile Time Error  
   obj.msg();//Compile Time Error  
  }  
}  

In the above example, the scope of class A and its method msg() is default so it cannot be accessed from outside the package.

3. Protected

The protected access modifier can be used both inside and outside of the package, but only through inheritance.

The protected access modifier can be applied on the data member, method and constructor. It can't be applied on the class.

It provides more accessibility than the default modifer.

Example

In this example, we have created the two packages pack and mypack. The A class of pack package is public, so can be accessed from outside the package. But msg method of this package is declared as protected, so it can be accessed from outside the class only through inheritance.

//save by A.java  
package pack;  
public class A{  
    protected void msg()
    {
        System.out.println("Hello");
    }  
} 
    

//save by B.java  
package mypack;  
import pack.*;  
  
class B extends A{  
  public static void main(String args[]){  
   B obj = new B();  
   obj.msg();  
  }  
}  

4. Public

The public access modifier is accessible everywhere. It has the widest scope among all other modifiers.

Example

//save by A.java  
  
package pack;  
public class A{  
    public void msg()
    {
        System.out.println("Hello");
        
    }  
}  

//save by B.java  
  
package mypack;  
import pack.*;  
  
class B{  
  public static void main(String args[]){  
   A obj = new A();  
   obj.msg();  
  }  
}  
With this article at Logicmojo, you must have the complete idea of Access Modifiers in OOPs.





Frequently Asked Questions (FAQs)



• In object-oriented programming (OOP), access modifiers are terms or properties that specify the visibility or accessibility of class members like variables, methods, and constructors. They define which program components may access or alter these members.

• Enforcing encapsulation and managing the accessibility of class members depend heavily on access modifiers. They aid in ensuring that information and conduct within a class are adequately restricted and only available to the essential components of the program.

• Public, private, protected, and package/default are the four main categories of access modifiers found in the majority of OOP languages.

• You can regulate the visibility and accessibility of class members in accordance with the program's design specifications by utilizing these access modifiers. As a result, illegal access or change to the data is prevented. By enabling regulated interaction between classes and objects, it also supports code reuse, maintainability, and separation of responsibilities.

• It's critical to pick access modifiers that are suitable for your program's intended use and design principles. You can build reliable and secure object-oriented systems by carefully controlling access.



Public, private, protected, and package/default are the four categories of access modifiers that are frequently employed in object-oriented programming (OOP). Let's investigate each of them in more depth:

Public:

The public access modifier enables access to class members (variables, methods, and constructors) from any location in the program, including outside the class. Public members are the most visible and accessible to all classes and objects. They are generally employed to offer APIs or interfaces through which other program components can communicate. For instance, any other class, whether it is in the same package or a different package, may call a public method in a class.

Private:

The private access modifier limits a class's members' visibility to only other members of that class. Private members, including those of its subclasses, cannot be accessible from outside the class. They are used to encapsulate implementation details and are designed for use exclusively within the class. Making members private ensures that they cannot be changed or directly accessed by outside parties. Private members are frequently used to protect data integrity and conceal a class's internal operations.

Protected:

Within the same class and its subclasses (derived classes), members of the class may be accessed using the protected access modifier. Members that are protected cannot be accessed from outside the class hierarchy. They give subclasses a level of visibility that allows them to access and alter particular features of the base class. When you want to expose specific behavior or data to subclasses while still limiting direct access from unrelated classes, protected members are frequently employed. They help to implement the "is-a" relationship between classes and promote inheritance.

Package/Default:

When no access modifier is expressly stated, the package or default access modifier is applied. It permits access to class members from the same package or module, but not from outside. This access level ensures that only relevant classes inside the package can access the members by providing a level of visibility that is restricted to a certain package. Package access encourages encapsulation within a package and hinders the direct access or modification of members by unrelated classes. If no access modifier is supplied, it is the level of access that is given to members by default.




Access modifiers in object-oriented programming (OOP) can be understood through real-life examples that demonstrate the concept of visibility and accessibility.

Imagine you have a car manufacturing company with different departments responsible for specific tasks. Each department has employees with different roles and responsibilities. Let's see how access modifiers relate to this scenario:

1. Public Access Modifier:

Consider the Sales department in your car manufacturing company. The Sales department has a public showroom where customers can come and view the cars. The showroom is accessible to anyone, whether they are from inside the company or outside. This is similar to the public access modifier, where class members are accessible from anywhere in the program.

2. Private Access Modifier:

In the manufacturing process, the Engineering department works on designing and building the car components. Within the department, there may be sensitive information or trade secrets that should not be accessed by employees from other departments or outside the company. This information is kept private and accessible only to the employees within the Engineering department. This aligns with the private access modifier, where class members are restricted to the same class and not accessible from outside.

3. Protected Access Modifier:

Now, consider the Manufacturing department responsible for assembling the car parts. The department has specialized tools and equipment that should only be used by employees within the Manufacturing department or by employees in specific sub-departments, such as Quality Control. These tools are protected and can be accessed by authorized individuals within the department or its subclasses. This is similar to the protected access modifier, where class members are accessible within the same class and its subclasses.

4. Package/Default Access Modifier:

In your car manufacturing company, you have different departments such as Sales, Engineering, Manufacturing, and Finance. Each department has its own workspace and resources. Within each department, the employees have access to their respective workspace and resources, but they may not have direct access to resources in other departments. This is similar to the package/default access modifier, where class members are accessible within the same package or module but not from outside.

These real-life examples help illustrate how access modifiers control the visibility and accessibility of class members in a program, similar to how different departments in a company have different levels of access to information, resources, and facilities. By using access modifiers appropriately, you can ensure proper encapsulation, data protection, and controlled interaction between different parts of your software system, just as different departments operate within their defined boundaries and permissions.




There are typically three types of access specifiers used in object-oriented programming (OOP) to specify the visibility or accessibility of class members (variables, methods, and constructors). The degree of access to class members from other areas of the program is managed using these access specifiers. The various access specifier types include the following:

1. Public:

The class members have unfettered access thanks to the public access specifier. From any location in the program, including from outside the class, you can access public members. They can be utilized by any other class or object and have the greatest visibility. This access specifier is frequently used to specify variables or methods that are a part of a class's public interface and give access to the required functionality.

2. Private:

Access is limited to class members only within the same class when the private access specifier is used. Private members, including those of its subclasses, cannot be accessible from outside the class. They are used to encapsulate implementation details and are designed for use exclusively within the class. Making members private ensures that they cannot be changed or directly accessed by outside parties. This access specifier is frequently used to uphold data integrity and enforce data encapsulation.

3. Protected:

Access to the class members of the same class and its derived classes is permitted by the protected access specifier. Members that are protected cannot be accessed from outside the class hierarchy. They give subclasses a level of visibility that allows them to access and alter particular features of the base class. This access specifier is frequently used to grant derived classes controlled access, allowing them to extend and inherit the behavior of the base class while limiting access to unrelated classes.

It's important to note that while access specifier availability and behavior may differ slightly amongst programming languages, the underlying ideas do not. Access specifiers are essential for maintaining encapsulation, managing visibility, and regulating how various components of an object-oriented program interact with one another.




In Java, there are four access modifiers that control the visibility or accessibility of class members (variables, methods, and constructors). These access modifiers are:

• 1. Public: Public members have the widest visibility and can be accessed from anywhere in the program, both within the class itself and from outside the class.

• 2. Private: Private members are accessible only within the same class. They cannot be accessed from outside the class, including its subclasses.

• 3. Protected: Protected members are accessible within the same class, its subclasses (derived classes), and other classes in the same package.

• 4. Default (no modifier): If no access modifier is specified, it is known as the default or package-private access. Default members are accessible within the same package but not from outside.

In addition to these access modifiers, Java also has eight non-access modifiers, also known as "modifiers" or "keywords," that provide additional functionality and behavior. These modifiers are not related to the visibility or accessibility of class members but affect other aspects of the program. The eight non-access modifiers are:

• 1. Static: The static modifier is used to declare static members (variables and methods) that belong to the class itself rather than specific instances of the class.

• 2. Final: The final modifier is used to mark a member as unchangeable or non-overridable. For variables, it indicates a constant value, and for methods, it prevents them from being overridden in subclasses.

• 3. Abstract: The abstract modifier is used to declare an abstract class or method. Abstract classes cannot be instantiated, and abstract methods do not have an implementation and must be overridden in subclasses.

• 4. Synchronized: The synchronized modifier is used to ensure that only one thread at a time can access a synchronized method or block, ensuring thread safety in multithreaded environments.

• 5. Volatile: The volatile modifier is used for variables to indicate that their value may be modified by different threads, ensuring visibility and proper synchronization in multithreaded environments.

• 6. Transient: The transient modifier is used for variables to indicate that they should not be serialized when an object is converted to a byte stream.

• 7. Native: The native modifier is used to indicate that a method is implemented in a platform-dependent or native programming language, such as C or C++, and not in Java.

• 8. Strictfp: The strictfp modifier is used for classes or methods to ensure that floating-point computations are performed consistently across different platforms, ensuring

platform-independent results.

These modifiers provide additional control and behavior beyond the accessibility of class members, allowing developers to define specific characteristics and restrictions for their code.




Access modifiers are an essential aspect of object-oriented programming (OOP) that serve multiple purposes in enhancing the design, security, and maintainability of software systems. Let's delve into the reasons why access modifiers are crucial in OOP:

1. Encapsulation and Information Hiding:

Access modifiers support the principle of encapsulation, which is a fundamental concept in OOP. Encapsulation involves bundling related data and behavior together in a class and controlling access to them. Access modifiers enable the encapsulation of data by specifying the visibility of class members.

By using access modifiers, such as private or protected, you can hide the internal details of a class from external entities. This helps in preventing unauthorized access, ensuring that the class's internal state remains consistent and protected. Encapsulation provides a clean interface for interacting with a class, promoting code maintainability and reducing dependencies.

2. Data and Behavior Integrity:

Access modifiers play a crucial role in maintaining the integrity and consistency of data and behavior within a class. By making certain members private, you prevent direct modification or access from external parts of the program. This helps in controlling how data is manipulated and ensures that it is modified through defined methods or functions, maintaining data integrity.

3. Security:

Access modifiers contribute to the security of a software system by restricting access to sensitive or critical parts of the code. By marking certain members as private, you prevent unauthorized access and modifications from other classes or external sources. This helps in protecting sensitive data and preventing potential security vulnerabilities.

4. Controlled Access and Modularity:

Access modifiers enable controlled access to class members, allowing for the creation of well-defined interfaces between classes. By selectively exposing only necessary members using public or protected access, you can establish clear boundaries and reduce dependencies between classes. This promotes modularity, making it easier to understand, modify, and maintain code.

5. Inheritance and Polymorphism:

Access modifiers play a significant role in inheritance and polymorphism, two fundamental concepts in OOP. Inheritance allows a class to inherit properties and behavior from its parent class. Access modifiers define the visibility of inherited members in derived classes. This ensures that subclasses can access and override appropriate members, maintaining the intended behavior and encapsulation.

6. Code Documentation and Readability:

Access modifiers also enhance code documentation and readability. By explicitly specifying access levels, developers can easily understand the intended visibility and accessibility of class members. This makes the code more self-explanatory and helps other developers in understanding and utilizing the class properly.

Overall, access modifiers provide control and flexibility in managing the visibility and accessibility of class members. They enforce encapsulation, enhance security, promote modularity, and contribute to the overall robustness and maintainability of object-oriented software systems. Proper use of access modifiers helps in designing well-structured code that is easier to understand, modify, and extend over time.




• Private members in object-oriented programming (OOP) are not directly accessible or visible outside the class that defines them. They are intended for internal use within the class and are used to encapsulate implementation details. This ensures that private members are not modified or accessed directly by external entities, promoting data integrity and encapsulation.

• However, there are ways to indirectly access private members from outside the class. One common approach is to use public methods, often called getters and setters or accessors and mutators. These methods provide controlled access to private members by exposing them through a public interface.

• Getters are public methods that allow retrieving the value of a private member, providing read access. Setters, on the other hand, are public methods that allow modifying the value of a private member, providing write access. By defining these public methods in the class, you can control how private members are accessed or modified from outside.

• You can uphold correct encapsulation and keep control over private members by utilizing getters and setters. It adds a layer of abstraction and guarantees the integrity of the data by enabling you to carry out additional operations or validations when accessing or changing private members.

• It's vital to remember that not all private members are required to use getters and setters. It depends on the course's requirements and design. While some private members might not need public access, others could need further reasoning or validation before they can be accessed or changed.



• Access level modifiers, also known as access modifiers or visibility modifiers, are keywords used in programming languages, particularly in object-oriented programming (OOP), to control the accessibility or visibility of class members (variables, methods, and constructors). They define the level of access that other parts of the program have to these members.

• Access level modifiers allow you to specify the boundaries of access to class members, ensuring proper encapsulation, data hiding, and controlled interaction between different parts of the program. They help enforce information hiding and maintain the integrity of data and behavior within a class.

• By using these access level modifiers, you can define the visibility and accessibility of class members based on your program's requirements. This helps in establishing appropriate boundaries, enhancing security, promoting code maintainability, and ensuring proper interaction between different parts of the program.



Access modifiers are language-specific and may vary across programming languages. While most object-oriented programming languages provide access modifiers, their syntax and behavior might differ. Let's explore this in more detail:

1. Java:

Java, being one of the most popular object-oriented programming languages, includes the concepts of access modifiers. In Java, the access modifiers include public, private, protected, and the default (package-private) access. These modifiers control the visibility and accessibility of class members.

2. C++:

C++ also supports access modifiers, but with some differences compared to Java. C++ includes public, private, and protected access modifiers. The public and private access modifiers in C++ work similarly to Java, controlling the visibility of class members. However, the protected access modifier in C++ allows access within the same class, derived classes, and friend classes, which differs from Java's protected access.

3. C#:

C# is another language that incorporates access modifiers. C# access modifiers include public, private, protected, internal, and protected internal. The public, private, and protected access modifiers in C# function similarly to their counterparts in Java and C++. The internal access modifier allows access within the same assembly, while the protected internal access modifier combines the behavior of protected and internal, allowing access within the same assembly and derived classes.

4. Python:

Python, although not traditionally considered an object-oriented programming language, supports access modifiers through naming conventions. By convention, a single leading underscore (_) indicates a member as "protected," suggesting that it should not be accessed outside the class or subclass. However, this is merely a convention, and the member can still be accessed externally.

5. Ruby:

Ruby, like Python, does not have built-in access modifiers, but it follows a convention using symbols. A single leading underscore (_) indicates a member as "protected," while a double leading underscore (__) suggests a member as "private." However, similar to Python, these conventions are not enforced by the language itself.

It's important to note that while access modifiers exist in various languages, their specific behavior and semantics may differ. Some languages may have additional access modifiers or variations on how they are applied. Therefore, it's essential to refer to the specific language documentation or guidelines to understand the precise usage and behavior of access modifiers in a particular programming language.





No, it is not advisable to make all members public. While the public access modifier allows unrestricted access to class members, it goes against the principles of encapsulation and information hiding, which are fundamental concepts in object-oriented programming (OOP). Exposing all members publicly can lead to potential misuse, insecure access, and difficulties in maintaining and modifying the code.

Here are some reasons why it is generally recommended to make members private by default and provide public methods (getters, setters, or other public interfaces) to control access to them:

1. Encapsulation and Information Hiding:

Encapsulation is the practice of bundling related data and behavior together within a class and controlling access to them. By making members private, you encapsulate the implementation details and hide them from external entities. This promotes data integrity, as access to the members is restricted and controlled. Public methods, also known as accessors and mutators, allow controlled access to the private members, ensuring that proper validation or logic is applied.

2. Data and Behavior Integrity:

By making members private, you prevent direct modification or access from external parts of the program. This helps in maintaining the integrity and consistency of data and behavior within the class. By providing public methods to interact with the private members, you can enforce rules, validation, or additional logic, ensuring that the data is accessed and modified in a controlled manner.

3. Security:

Exposing all members publicly can pose security risks, as they can be accessed and modified by any part of the program. This can lead to unintended modifications or unauthorized access to sensitive data. By making members private, you limit their visibility and reduce the potential attack surface, enhancing the security of your code.

4. Code Maintainability and Flexibility:

By encapsulating implementation details and providing controlled access through public methods, you establish a clear interface for interacting with a class. This separation between the public interface and the internal implementation allows you to modify the implementation without affecting the external usage. It also makes the code more maintainable, as changes to the internal implementation do not require modifications to the code using the class. Additionally, public methods can incorporate additional functionality or modifications as the code evolves, ensuring backward compatibility.

5. Dependency Management and Modularity:

By exposing only the necessary functionality through a well-defined public interface, you reduce dependencies between different parts of the program. This promotes modularity, making it easier to understand, modify, and test the code. It also allows for easier code maintenance and future enhancements.

In summary, it is generally recommended to make members private by default and provide public methods or interfaces to control access to them. This approach promotes encapsulation, data integrity, security, code maintainability, and modularity. By carefully managing access and following the principles of OOP, you can design code that is more robust, maintainable, and secure.





Protected members in object-oriented programming (OOP) are accessible within the same class, its subclasses (derived classes), and sometimes across packages ( depending on the programming language). This allows protected members to be accessed outside the subclass, but there are specific conditions to consider.

1. Access within the Same Class:

Protected members can be accessed directly within the same class where they are defined. This means that any code within the class can access and modify protected members without any restrictions.

2. Access within Subclasses:

Protected members can also be accessed within subclasses or derived classes. When a class extends another class to create a subclass, it inherits the protected members of the superclass. This inheritance allows the subclass to access and modify protected members of the superclass.

3. Access across Packages (depending on the programming language):

In some programming languages, such as Java, protected members can also be accessed across packages as long as there is an inheritance relationship between the classes. This means that if the accessing class is a subclass (derived class) located in a different package, it can access the protected members of the superclass.

However, it's important to note that the accessibility of protected members across packages may vary depending on the programming language and its specific rules for access modifiers.

For example, in C++, protected members are only accessible within the class hierarchy and are not accessible from classes outside the hierarchy, regardless of the package.

To summarize, protected members can be accessed outside the subclass in the following scenarios:

- They can be accessed within the subclass itself.

- They can be accessed within any subclass that inherits from the class where the protected members are defined.

- They can be accessed across packages (depending on the programming language) if the accessing class is a subclass in a different package and there is an inheritance relationship.

Protected access allows for a controlled level of visibility, providing subclass-specific access to certain members while still maintaining encapsulation. It facilitates the "is-a" relationship between classes and allows for overriding and extending the behavior of the superclass in subclasses.