GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing www.geeksforgeeks.org — Access Modifiers in Java - GeeksforGeeks Access Modifiers in JavaLast Updated : 28 Sep, 2026 Access modifiers in Java are used to control the visibility and accessibility of classes, methods, and variables. They help enforce encapsulation by restricting access to different parts of a program. Java provides four types of access modifiers to define scope and protection levels.
Types of Access ModifiersThere are 4 types of access modifiers available in Java: ![]() 1. Private Access ModifierThe private access modifier is specified using the keyword private. The methods or data members declared as private are accessible only within the class in which they are declared.
Output Alice Explanation: Direct access to name is not allowed outside Person, enforcing encapsulation. 2. Default Access ModifierIf no access modifier is specified, this means only classes within the same package can access it.
Output Tesla Explanation: Members with default access cannot be accessed from classes in a different package. Geeks.java: Default class within the same package
GeeksNew.java: Default class from a different package (for contrast)
Explanation: In this example, the program will show the compile-time error when we try to access a default modifier class from a different package. 3. Protected Access ModifierThe protected access modifier is specified using the keyword protected. The methods or data members declared as protected are accessible within the same package or subclasses in different packages.
Output Access via subclass method: 100 0 Explanation: speed is accessible via subclass methods and other classes in the same package, but direct access from a different package (non-subclass) would fail. 4. Public Access ModifierThe public access modifier is specified using the keyword public. Public members are accessible from everywhere in the program. There is no restriction on the scope of public data members.
Output 15 Explanation: add() is globally accessible due to the public modifier. Top-level classes or interfaces can not be declared as private because, private means "only visible within the enclosing class". Comparison Table of Access Modifiers in Java![]() When to Use Access Modifier in Real-World Projects
Comment Explore |
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |