Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

ความแตกต่างระหว่าง protected และ default access specifiers ใน Java

Protected access specifier มองเห็นได้ภายในแพ็กเกจเดียวกัน และ มองเห็นได้ในคลาสลูก (subclass) ส่วน Default เป็น package-level access specifier และ มองเห็นได้เฉพาะในแพ็กเกจเดียวกัน

Protected Access Specifier

  • Protected ทำงานเหมือน public ภายในแพ็กเกจเดียวกัน และทำงานเหมือน private นอกแพ็กเกจ
  • Protected ทำงานเหมือน public นอกแพ็กเกจ แต่เฉพาะกับออบเจ็กต์ของ subclass เท่านั้น
  • Protected fields หรือ methods ไม่สามารถใช้กับ classes และ interfaces ได้
  • Fields, methods, และ constructors ที่ประกาศเป็น protected ใน superclass สามารถเข้าถึงได้เฉพาะโดย subclasses ในแพ็กเกจอื่น
  • คลาสในแพ็กเกจเดียวกันก็สามารถเข้าถึง protected fields, methods และ constructors ได้เช่นกัน แม้จะไม่ใช่ subclass ของคลาสที่มี protected member

ตัวอย่าง

public class ProtectedTest {
    // variables that are protected
    protected int age = 30;
    protected String name = "Adithya";
    /**
     * This method is declared as protected.
     */
    protected String getInfo() {
        return name + " is " + age + " years old.";
    }
    public static void main(String[] args) {
        System.out.println(new ProtectedTest().getInfo());
    }
}

ผลลัพธ์

Adithya is 30 years old.

Default Access Specifier

  • สมาชิกของคลาสที่กล่าวถึง โดยไม่มี access specifier ถือว่าเป็น Default
  • Default ทำงานเหมือน public ภายในแพ็กเกจเดียวกัน และทำงานเหมือน private นอกแพ็กเกจ
  • สมาชิก Default ของคลาสใดๆ สามารถเข้าถึงได้ภายในแพ็กเกจเดียวกัน และ ไม่สามารถเข้าถึงได้นอกแพ็กเกจในทุกกรณี
  • Default จำกัดการเข้าถึงเฉพาะ ระดับแพ็กเกจ แม้จะ extends คลาสที่มี default data members ก็ไม่สามารถเข้าถึงได้

ตัวอย่าง

public class DefaultTest {
    // variables that have no access modifier
    int age = 25;
    String name = "Jai";
    /**
     * This method is declared with default access specifier
     */
    String getInfo() {
        return name + " is " + age + " years old.";
    }
    public static void main(String[] args) {
        System.out.println(new DefaultTest().getInfo());
    }
}

ผลลัพธ์

Jai is 25 years old.