0
0
Javaprogramming~15 mins

Public access modifier in Java - Step-by-Step Execution

Choose your learning style8 modes available
flowchartConcept Flow - Public access modifier
Declare public class or member
Accessible from anywhere
Use in same class, package, or other packages
No access restrictions
Program runs
The public access modifier allows classes, methods, or variables to be accessed from any other class or package without restriction.
code_blocksExecution Sample
Java
public class Car {
    public String model = "Tesla";
    public void display() {
        System.out.println(model);
    }

    public static void main(String[] args) {
        Car c = new Car();
        c.display();
    }
}
This code defines a public class with a public variable and method, then creates an object and calls the method to print the model.
data_tableExecution Table
StepActionEvaluationResult
1Create object c of class Carnew Car()Object c created with model = "Tesla"
2Call c.display()c.display()Prints: Tesla
3Access c.model directlyc.modelReturns "Tesla"
4Try access from another class/packageAccess public memberAllowed, no error
5End of execution--
💡 Program ends after printing the model and demonstrating public access
search_insightsVariable Tracker
VariableStartAfter Step 1After Step 2Final
cnullCar object with model="Tesla"Car object with model="Tesla"Car object with model="Tesla"
modelnull"Tesla""Tesla""Tesla"
keyKey Moments - 2 Insights
Why can we access the variable 'model' directly from object 'c'?
What happens if we try to access a non-public member from another package?
psychologyVisual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is printed when c.display() is called at step 2?
AError
Bnull
CTesla
DNothing
photo_cameraConcept Snapshot
public modifier allows access from anywhere
Used on classes, methods, variables
No restrictions on visibility
Syntax: public type name
Example: public int count;
contractFull Transcript
The public access modifier in Java means that the class, method, or variable can be accessed from any other class or package without restriction. In the example, a public class Car has a public variable model and a public method display. When we create an object c of Car and call c.display(), it prints the model name 'Tesla'. Because model is public, we can also access c.model directly from anywhere. If a member is not public, accessing it from another package would cause a compile error. Public is the most open access level in Java.