The protected modifier allows a member to be accessed within its package and by subclasses in other packages.
A protected member can be used by all subclasses, but remains protected from access by code outside the package.
An example can help you better understand the effect of protected.
In the example, the Book class is changed so that its instance variables are protected.
Create a subclass of Book called ExtBook.
Create a class called ProtectDemo that uses ExtBook.
ExtBook adds a field to store the publisher name.
ExtBook also has several accessor methods.
The two classes (ExtBook and ProtectDemo) are in the bookpackext package.
ExtBook extends Book, which allows you to access protected Book members, even though they are in different packages.
ExtBook can directly access protected members such as title, author, and pubDate, creating accessor methods for these variables.
In the ProtectDemo class, direct access to these variables is denied because ProtectDemo is not a subclass of Book.
If the comment is removed from the books[0].title = "test title"; line, the program will not compile due to access restriction.
The above is the detailed content of Understanding Protected Members. For more information, please follow other related articles on the PHP Chinese website!