0
0
Javaprogramming~15 mins

Public access modifier in Java

Choose your learning style8 modes available
menu_bookIntroduction

The public access modifier allows other parts of your program to use a class, method, or variable freely. It makes things open and easy to reach.

When you want a class to be used by any other class in your program.
When you want a method to be called from anywhere in your code.
When you want a variable to be accessible from any other class.
When creating a main method that the Java runtime needs to access.
When sharing utility methods that many parts of your program need.
regular_expressionSyntax
Java
public class ClassName {
    public int number;
    public void methodName() {
        // code
    }
}

Use public before class, method, or variable to make it accessible everywhere.

Public members can be accessed from any other class in any package.

emoji_objectsExamples
line_end_arrow_notchThis class and its members can be used anywhere in your program.
Java
public class Car {
    public String model;
    public void start() {
        System.out.println("Car started");
    }
}
line_end_arrow_notchThis variable can be accessed from any other class.
Java
public int count = 10;
line_end_arrow_notchThis method can be called from any other class.
Java
public void greet() {
    System.out.println("Hello!");
}
code_blocksSample Program

This program uses public members so the main method can create an object and call the printMessage method to show the message.

Java
public class HelloWorld {
    public String message = "Hello, world!";

    public void printMessage() {
        System.out.println(message);
    }

    public static void main(String[] args) {
        HelloWorld hw = new HelloWorld();
        hw.printMessage();
    }
}
OutputSuccess
emoji_objectsImportant Notes
line_end_arrow_notch

Public members are easy to use but be careful not to expose sensitive data.

line_end_arrow_notch

Use public only when you want others to access the member freely.

list_alt_checkSummary

Public means open and accessible from anywhere.

Use it for classes, methods, or variables you want to share freely.

It helps different parts of your program work together easily.