Java Access Modifiers and Package-Level Access

 

🔐 Java Access Modifiers and Package-Level Access

Java provides four access levels:

Access ModifierClass    Package    Subclass    World (outside package)
public                                
protected                            
(default) no modifier                            
private                                    

📦 How It Works in Packages

1. public

  • Accessible from any class in any package.

  • Typically used when a class or method needs to be globally available.

Example:


package mypack; public class A { public void show() { System.out.println("Public method"); } }

2. protected

  • Accessible within the same package and also by subclasses in other packages.

  • Often used in inheritance scenarios.

Example:


package mypack; public class A { protected void display() { System.out.println("Protected method"); } }

package otherpack; import mypack.A; class B extends A { void callDisplay() { display(); // Valid because B is a subclass of A } }

3. Default (no modifier)

  • Package-private: accessible only within the same package.

  • Used when you want a class or method to be hidden from other packages.

Example:

package mypack;
class A { // default class void show() { System.out.println("Default access method"); } }
  • This class A cannot be accessed from a class in a different package.

4. private

  • Accessible only within the same class.

  • Not accessible from other classes even in the same package.

  • Commonly used for data hiding.

Example:


package mypack; public class A { private int x = 5; private void display() { System.out.println("Private data: " + x); } }

🧠 Key Points for Instructors

  • Default access is often misunderstood — remind students it's only package-level.

  • protected offers the most nuanced behavior, useful when mixing packages and inheritance.

  • Best practice: make class members private, then expose functionality using public or protected methods if needed.


✅ Summary Table

Modifier    Accessible in Same Class        Same Package        Subclass (other package)        Unrelated Class (other package)
public                                        
protected                                        
default                                        
private                                            

Comments

Popular posts from this blog

Object Oriented Programming PBCST304 KTU BTech CS Semester 3 2024 Scheme - Dr Binu V P

Introduction to Java Programming

Inheritance and Polymorphism