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 ProtectDemon 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.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3