Looking For Anything Specific?

ads header

Understanding the protected access modifier in Java.

 In Java, both protected and default access modifiers are used to control access to class members. However, there are some key differences between the two.



 The protected modifier makes a class member accessible within the class itself, within any subclasses of the class, and within any other classes in the same package as the class. This means that subclasses and other classes in the same package can access protected members, but classes outside the package cannot. 


On the other hand, the default access modifier makes a class member accessible only within the same package as the class. This means that any class in the same package can access default members, but classes outside the package cannot. 



Here's an example to illustrate the differences:



package com.example;


public class MyClass {

    protected int x = 5; // protected access


    int y = 10; // default access

}


package com.example.subpackage;


import com.example.MyClass;


public class Subclass extends MyClass {

    public void doSomething() {

        System.out.println(x); // Output: 5 (accessed from subclass)

        System.out.println(y); // Compile error (y has default access)

    }

}


package com.example.anotherpackage;


import com.example.MyClass;


public class AnotherClass {

    public void doSomething() {

        MyClass myClass = new MyClass();

        System.out.println(myClass.x); // Compile error (x has protected access)

        System.out.println(myClass.y); // Compile error (y has default access)

    }

}

 


Post a Comment

0 Comments