سؤال

I create a class, that has a few protected members, that are completely accessible to other classes:

class MyClass {
    protected String name;
}

In my opinion, this shouldn't compile:

MyClass mc = new MyClass();
mc.name = "foo";

but it works fine. When I make the member private, it works as expected. How could this be?

A few notes, but they shouldn't make any difference I think:

  • the mc is inside a HashMap,
  • I access it inside an Activity
هل كانت مفيدة؟

المحلول

protected members are accessible in subclasses(in same or different package) and all the classes in the same package. If you move that code to a different package, you would get the expected behaviour.

See Access Control.

نصائح أخرى

The oracle docs are defining protected as followes:

The protected modifier specifies that the member can only be accessed within its own package (as with package-private) and, in addition, by a subclass of its class in another package.

See this Link

This means if you move your Class to another package you cannot acces the name.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top