⬅ Previous Topic
Java protected KeywordNext Topic ⮕
Java return Keyword⬅ Previous Topic
Java protected KeywordNext Topic ⮕
Java return Keywordpublic
Keyword in JavaIn Java, the public
keyword is an access modifier. It's used to define the visibility of classes, methods, constructors, and variables across different packages. When something is marked as public
, it means that it can be accessed from anywhere — within the same class, same package, subclass, or from completely unrelated classes in other packages.
public
?Java is built around the principle of encapsulation, and access modifiers like public
help control that access. You use public
when you want your component to be accessible globally. It’s common for main classes, APIs, and utility methods.
A public
class must be declared in a file with the same name as the class. This is often used when defining entry-point classes for your applications.
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, world!");
}
}
Hello, world!
Explanation: The class HelloWorld
is declared public
, so it can be accessed from anywhere. The main
method is also public
so the JVM can call it.
Marking a method public
makes it callable from any other class, even in other packages.
public class Calculator {
public int add(int a, int b) {
return a + b;
}
}
public class Demo {
public static void main(String[] args) {
Calculator calc = new Calculator();
System.out.println(calc.add(5, 3));
}
}
8
Explanation: The add
method is public
, so it can be accessed from the Demo
class even if they are in separate packages (provided proper import).
Although not recommended (due to encapsulation best practices), variables can also be marked public
if you want direct access.
public class Dog {
public String breed = "Labrador";
}
public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
System.out.println(dog.breed);
}
}
Labrador
Explanation: Here, the breed
variable is directly accessible. However, in practice, it’s better to use private variables with public getters/setters.
Constructors can also be made public
so that objects can be created freely.
public class Book {
public Book() {
System.out.println("Book created!");
}
}
public class Library {
public static void main(String[] args) {
Book b = new Book();
}
}
Book created!
Explanation: The constructor is public, so any other class can create an instance of Book
.
public
default
.private
.protected
.public
.Usage | Accessible From |
---|---|
public class |
Everywhere |
public method |
All classes, packages |
public variable |
Globally (not recommended) |
public constructor |
Anyone can instantiate |
⬅ Previous Topic
Java protected KeywordNext Topic ⮕
Java return KeywordYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.