🚪
OOP

Access Modifiers और Packages

Who Can See What
💡 Access modifiers घर के दरवाज़ों जैसे हैं — public दरवाज़ा सबके लिए खुला, private सिर्फ़ तुम्हारे अपने कमरे का, protected सिर्फ़ family (subclass) के लिए, और default सिर्फ़ same colony (package) के लोगों के लिए।

public: कहीं से भी access हो सकता है। private: सिर्फ़ उसी class के अंदर। protected: same package + subclasses में। default (कुछ ना लिखो): सिर्फ़ same package में।

Package related classes का एक folder/group है — जैसे java.util में List, Map जैसे collection classes होते हैं। अपना package बनाने के लिए "package com.code10x;" लिखते हैं।

package com.code10x;

public class Robot {
  private int battery;
  protected void charge() { battery = 100; }
}
🚪
Access modifiers घर के दरवाज़ों जैसे हैं — public दरवाज़ा सबके लिए खुला, private सिर्फ़ तुम्हारे अपने कमरे का, protected सिर्फ़ family (subclass) के लिए, और default सिर्फ़ same colony (package) के लोगों के लिए।
1 / 6
⚡ झट से Recap
  • public/private/protected/default = 4 levels
  • Package = related classes का group
  • Encapsulation के लिए access control ज़रूरी
इस page में (4 subtopics)

Java में 4 access levels हैं, और इनका effect depend करता है कि accessing code कहाँ से है — same class, same package, subclass (चाहे अलग package में हो), या पूरी दुनिया (कोई भी जगह)।

ModifierSame ClassSame PackageSubclass (diff package)World
public
protected
default (कुछ ना लिखो)
private
💡Tip: Rule of thumb: हमेशा सबसे restrictive access से शुरू करो (private), और सिर्फ़ तभी ज़्यादा खोलो (protected/public) जब genuinely ज़रूरत हो। ये "principle of least privilege" है — accidental misuse रोकता है।

हर .java file top पर "package com.code10x.model;" लिख सकती है — folder structure package नाम से match करना चाहिए (com/code10x/model/ folder में file होनी चाहिए)। दूसरी जगह use करने के लिए "import com.code10x.model.Student;" लिखते हैं, या पूरे package के लिए import com.code10x.model.*;

java.lang package (String, Integer, System, etc.) automatically हर file में import होता है, explicit import की ज़रूरत नहीं।

import static से static members बिना class-prefix के directly use कर सकते हो — जैसे import static java.lang.Math.*; के बाद सीधा sqrt(25) लिख सकते हो, Math.sqrt(25) की जगह। ज़्यादा use करने से code confusing हो सकता है (पता नहीं चलता method कहाँ से आया) — इसलिए sparingly use करो, mainly test frameworks (JUnit के assertEquals) में common है।

Classpath JVM को बताता है कहाँ ढूँढे compiled .class files और libraries। Modern build tools (Maven, Gradle) automatically classpath manage कर देते हैं (dependencies download करके सही जगह रखते हैं), लेकिन समझना ज़रूरी है कि JVM runtime पर classes कैसे ढूँढती है — अगर "ClassNotFoundException" आए, अक्सर classpath issue होती है।