Video tayyorlanmoqda

Strong Junior 🧱 OOP va SOLID

`protected` modifikatori aslida kimlarga ko'rinadi?

Bola klasslarga va o'sha paketdagi barcha klasslarga. Ko'pchilik faqat "bola klasslar uchun" deb o'ylaydi, lekin bir paketdagi istalgan klass protected a'zoga bemalol murojaat qila oladi.

📖 Javob

Java'dagi to'rt daraja:

Modifikator Klass ichi Paket Bola klass (boshqa paket) Hamma
private ha yo'q yo'q yo'q
(yozilmagan) ha ha yo'q yo'q
protected ha ha ha yo'q
public ha ha ha ha

Ya'ni protected package-private'dan kengroq, torroq emas.

Yana bir nozik joy: boshqa paketdagi bola klass protected a'zoga faqat o'z turi orqali murojaat qila oladi:

// com.app.b paketida
class Child extends com.app.a.Parent {
    void test(Parent other, Child same) {
        this.secret();   // OK
        same.secret();   // OK
        other.secret();  // compile xatosi — boshqa Parent obyekti
    }
}

Amalda: maydonlarni protected qilishdan qoching — bu ham encapsulation'ni ochib qo'yadi. Bola klassga kerak bo'lsa, protected metod bering.