Question

public class MyTest {
    public static void main(String str[]){
        Info i=new Info();
        i.value=20;
        System.out.println("Integer value is :"+i.value);
    }
}
class Info {
    int value;
    protected Info(){
    System.out.println("Class with protected constructor");
    }
}

-->I am missing something about protected modifier but could not figure it out. -->Till now i have read that a class with protected constructor can only be instantiated by its Sub-Classes and that too in a same package or in a different package. Then how come the above is giving me this output : Class with protected constructor Integer value is :20

Était-ce utile?

La solution 2

Protected members are accessible from within Class, Same package and in Subclass. It doesn't have access to the World (other than mentioned above)

See the below table

The following table shows the access to members permitted by each modifier.

Access Levels
Modifier      Class    Package     Subclass         World
public          Y         Y            Y              Y
protected       Y         Y            Y              N
no modifier     Y         Y            N              N
private         Y         N            N              N

Autres conseils

Because, both classes, MyTest and Info are in same package.

Classes in the same package can access the protected members without any problems

If the member or constructor is declared protected, then access is permitted only when one of the following is true:

  • Access to the member or constructor occurs from within the package containing the class in which the protected member or constructor is
    declared.

Check JLS 6.6.2

What will you help in the long run is to know that ANYTHING protected can only be accessed and manipulated by its sub-classes. This includes methods, variables, etc. Classes located in the same package as a class with a protected constructor are still "aware" of the variables located within the constructor. Therefore, you are receiving your output "Class with protected constructor Integer value is :20" because the two classes are in the same package.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top