0

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
Prmths
  • 2,022
  • 4
  • 21
  • 38
Bart Friederichs
  • 33,050
  • 15
  • 95
  • 195

2 Answers2

6

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.

Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
2

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.

A.S.
  • 4,574
  • 3
  • 26
  • 43