Access modifiers in Java are used to set the accessibility and visibility of classes, methods, and variables. The four main access modifiers are:
Here is a simple example demonstrating the use of each access modifier:
class Example {
// Public variable
public String publicVar = "I am public!";
// Protected variable
protected String protectedVar = "I am protected!";
// Default variable
String defaultVar = "I am default!";
// Private variable
private String privateVar = "I am private!";
public void display() {
System.out.println(publicVar);
System.out.println(protectedVar);
System.out.println(defaultVar);
System.out.println(privateVar);
}
}
class Test {
public static void main(String[] args) {
Example example = new Example();
example.display();
// Accessing variables
System.out.println(example.publicVar); // Accessible
// System.out.println(example.protectedVar); // Not accessible
// System.out.println(example.defaultVar); // Not accessible
// System.out.println(example.privateVar); // Not accessible
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?