"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Understanding Protected Members

Understanding Protected Members

Published on 2024-11-04
Browse:624
  • 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.

Entendendo os membros protegidos

  • 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.

  • Entendendo os membros protegidos

  • Entendendo os membros protegidos

  • Entendendo os membros protegidos

  • 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.

Release Statement This article is reproduced at: https://dev.to/devsjavagirls/entendendo-os-membros-protegidos-3eg2?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

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