Java Public Access Modifier
Table of Contents + โ
In the last lesson you learned about the Java default access modifier. Sometimes you want the exact opposite: a class or method that anyone can use, no matter where their code lives. That is what the public keyword is for.
๐ค What problem does public solve?
Picture this. Alex writes a small library that converts temperatures. Riya wants to use it in her own project in a different package. She writes new TemperatureConverter() and the compiler says no. The class is not visible to her.
- By default, your code is private to its own package.
- Real software is built out of pieces written by many people.
- A library is useless if nobody outside its own folder can call it.
- The
publickeyword opens a class or method to the whole world: any package, any project.
๐ What does public actually mean?
The public modifier gives the widest possible access. A public member can be reached from anywhere: same class, same package, different package, even a different project that depends on yours. Here a class has a public field and a public method, both open to the entire program.
public class Account { public String owner; // open to everyone
public void greet() { // open to everyone System.out.println("Hello, " + owner); }}Anyone who can see the Account class can read owner and call greet(). Nothing stops them.
๐ Accessing a public member across packages
The real power of public shows up when code crosses package lines. This first file defines a public class with a public method in the bank package.
package bank;
public class Account { public String owner = "Alex";
public void showBalance() { System.out.println(owner + " has 500 dollars"); }}Now a second file in a different package imports that class and uses it:
package app;
import bank.Account;
public class Main { public static void main(String[] args) { Account a = new Account(); System.out.println(a.owner); // public field, reachable a.showBalance(); // public method, reachable }}Running Main prints this.
Output
AlexAlex has 500 dollarsBoth lines work. If Account had been default instead of public, the import bank.Account line alone would fail to compile, because the class would be invisible outside the bank package.
๐ Public classes and the filename rule
One rule trips up almost every beginner. A public class must live in a file with the exact same name.
- A public class named
Accountmust be inAccount.java. - Not
account.java. NotMyAccount.java. The name and the case must match.
This file is correct because the class name matches the filename Account.java.
public class Account { public void hello() { System.out.println("Hi from Account"); }}If you put that same class in a file named Bank.java, the compiler stops you.
Output
error: class Account is public, should be declared in a file named Account.javaWhen another class writes new Account(), the compiler finds Account fast because a public class is always in a file of its own name. This also leads to a second rule, which we hit again in Common Mistakes: a single .java file can have at most one public class.
๐งฐ Public methods and fields are your API
The public parts of your class are its API: the set of things the outside world is allowed to use.
- API stands for Application Programming Interface, the official list of what other code can call.
- Everything you mark
publicis a promise: โyou may rely on this, and I will try not to break itโ. - Think of a microwave. The buttons on the front are public. The wiring inside is hidden.
- The maker can rewire the inside freely without changing how you press the buttons.
This class shows the idea. The public methods are the buttons. The field is hidden inside.
public class Microwave { private int seconds; // hidden wiring
public void setTime(int s) { // a public button seconds = s; }
public void start() { // a public button System.out.println("Heating for " + seconds + " seconds"); }}Using it feels clean, because you only ever touch the buttons.
Microwave m = new Microwave();m.setTime(30);m.start();Output
Heating for 30 secondsThe caller never sees seconds. You expose a small set of public methods and hide the messy details behind them.
โ Why not make everything public?
If public is so handy, why not slap it on everything? Because it breaks encapsulation: keeping a classโs inner data hidden and protected. When a field is public, anyone can change it to anything, at any time, with no checks.
public class BankAccount { public int balance; // โ anyone can wreck this}Now any code, anywhere, can do this.
BankAccount acc = new BankAccount();acc.balance = -9999; // a negative balance, with no warningCaution
A public field has no guard. Nobody checks the value. A bank account just went negative and the class could not stop it.
There is a slower kind of pain too.
- Once a field is public, other peopleโs code depends on it directly.
- The day you rename it or change how it works, you break everyone who used it.
- The bigger your public surface, the harder your class is to change later.
- So keep public small. Expose only what callers truly need, and hide the rest.
โถ๏ธ Why is main always public?
You have written public static void main(String[] args) many times. Why must it be public?
- The Java Virtual Machine (the JVM, the engine that runs your code) calls
mainfrom outside your class. - The JVM is not part of your package, so
mainmust be reachable from anywhere. - Make it anything narrower and the program fails to start.
This is the standard, working form.
public class App { public static void main(String[] args) { System.out.println("Program started"); }}Output
Program startedRemove public and make main use default access, and the JVM cannot reach it.
Output
Error: Main method not found in class AppSo public on main is not a style choice. It lets the JVM find your starting point and run it.
โ ๏ธ Common Mistakes
Public fields instead of private fields with getters. Exposing data directly is the classic mistake. It removes every chance to validate or protect the value.
// โ Wrong: anyone can set any value, no checkspublic class User { public int age;}// โ
Right: hide the field, control access with methodspublic class User { private int age;
public int getAge() { return age; }
public void setAge(int age) { if (age >= 0) { this.age = age; } }}More than one public class in a single file. A .java file can hold only one public class, and the file must be named after it.
// โ Wrong: File Account.java with two public classespublic class Account { }public class Customer { } // compiler error// โ
Right: one public class per file, named to matchpublic class Account { }Put Customer in its own Customer.java file.
Making helper methods public by habit. A method used only inside the class does not belong in your API. Marking it public invites outsiders to depend on something they should never touch.
// โ Wrong: an internal step exposed to the worldpublic class Report { public void formatNumbers() { } // only used internally}// โ
Right: keep internal helpers privatepublic class Report { private void formatNumbers() { }}โ Best Practices
- Make a member
publiconly when code outside the package truly needs it. Default to hiding things. - Keep fields
privateand offerpublicgetters and setters so you stay in control of the data. - Treat your public methods as a contract. Once others rely on them, changing them breaks their code, so design them with care.
- One public class per file, and the filename must match the class name exactly, including the case.
- Keep
mainpublic so the JVM can start your program. - A small public surface is a feature, not a limit. The less you expose, the freer you are to improve the inside later.
๐งฉ What Youโve Learned
publicgives the widest access. A public class or member is reachable from anywhere, in any package or project.- Public members can be used across package boundaries, which is how libraries work.
- A public class must live in a file with the exact same name, and a file can hold only one public class.
- Public methods and fields form your classโs API, the official list of what callers may use.
- Marking everything public breaks encapsulation and makes your class hard to change. Keep public small.
mainmust be public so the JVM can call it from outside and start your program.
Check Your Knowledge
Test what you learned. Pick an answer for each question, then click Check.
- 1
Where can a public member be accessed from?
Why: public gives the widest access. It is reachable from any package or project.
- 2
A public class named Account must be in which file?
Why: A public class must live in a file with the exact same name and case, so Account.java.
- 3
Why should fields usually be private instead of public?
Why: A public field can be changed to anything with no checks, which breaks encapsulation.
- 4
Why must the main method be public?
Why: The JVM is outside your package, so main must be public for it to be found and called.
๐ Whatโs Next?
You have seen the most open modifier. Now letโs flip to the most closed one. Next we look at how to lock a member down so only its own class can touch it, which is the foundation of clean, safe class design.