Protected
This is the most common access modifier of the four. A class can only access a protected class method or attribute if it is a descendant of that class in the inheritance hierarchy. It is similar to private
, which we will discuss in the next paragraph. No matter where the descendant class is (perhaps in another package), we can access a class's methods/attributes if we inherit from that class.
If you look at the Shape
class hierarchy in the previous lesson, you'll now understand that Square
can access all of the properties of the Rectangle
and Shape
class because it is a descendant of both the Rectangle
and Shape
class. It cannot, however, access any protected method/attribute of the Circle
class because it is not inherited from that class.