Home > Java > javaTutorial > Understanding Protected Members

Understanding Protected Members

Patricia Arquette
Release: 2024-10-02 06:14:01
Original
605 people have browsed it
  • 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 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!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template