-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAccessModifiers.java
More file actions
34 lines (26 loc) · 1.03 KB
/
AccessModifiers.java
File metadata and controls
34 lines (26 loc) · 1.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class Person {
public String name; // Accessible anywhere
protected int age; // Accessible in same package
String country; // Default (package-private)
private String secret; // Accessible only in this class
Person(String name, int age, String country, String secret) {
this.name = name;
this.age = age;
this.country = country;
this.secret = secret;
}
// Public method to access private variable
public void showSecret() {
System.out.println("Secret: " + secret);
}
}
public class AccessModifiers {
public static void main(String[] args) {
Person p = new Person("John", 20, "Philippines", "Loves coding");
System.out.println(p.name); // ✅ public
System.out.println(p.age); // ✅ protected (same package)
System.out.println(p.country); // ✅ default (same package)
// System.out.println(p.secret); // ❌ ERROR: private
p.showSecret(); // ✅ access private via method
}
}