public access modifier in Java


A class, method, constructor, interface, etc. declared public can be accessed from any other class. Therefore, fields, methods, blocks declared inside a public class can be accessed from any class belonging to the Java Universe.

However, if the public class we are trying to access is in a different package, then the public class still needs to be imported. Because of class inheritance, all public methods and variables of a class are inherited by its sub classes.

Example

The following function uses public access control -

public static void main(String[] arguments) {
   // ...
}

The main() method of an application has to be public. Otherwise, it could not be called by a Java interpreter (such as java) to run the class.

Updated on: 24-Feb-2020

243 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements