Difference between public and private access modifiers in Java

Access modifiers in Java determine the level of visibility and accessibility of variables, methods, and classes. There are four main access modifiers in Java: public, private, protected, and default. In this article, we will focus on the difference between public and private access modifiers.

Public access modifier:

Public access modifier allows the variables, methods, and classes to be accessed from anywhere within the code. Variables or methods declared public are accessible to all classes, regardless of the package they belong to. Public access modifier makes the code more flexible and reusable. For instance, if you have a class with a public method, it can be called from any other class in your application.

Private access modifier:

Private access modifier limits the accessibility of variables, methods, and classes. Variables or methods declared private are only accessible within the same class. Private access modifier ensures that the code remains protected from accidental changes or manipulation. For instance, if you have a private method in your class, it can only be accessed from within that class and can't be called from other classes in your application.


Public Access Modifier Private Access Modifier
This modifier applies to first-level classes and interfaces. This modifier is not applicable for both top-level classes and interfaces.

Public members can be accessed from the child class of the same package.

Private members cannot be accessed from the child class of the same package.
Public member can be accessed from non-child class of same package. Private members cannot be accessed from non-child class of same package.
Public members can be accessed from child class of outside package. Private members cannot be accessed from child class of outside package.
Public members can be accessed from non-child class of outside package. Private members cannot be accessed from non-child class of outside package.
Public modifier is the most accessible modifier. Private modifier is the most restricted modifier.
Public modifier is the recommended modifier for method. Private modifier is the recommended modifier for data members.

Submit Your Programming Assignment Details