Understanding Protected Members

Newcomers to Java are sometimes confused by the meaning and use of protected. As explained, the protected modifier creates a member that is accessible within its package and to subclasses in other packages. Thus, a protected member is available for all subclasses to use but is still protected from arbitrary access by code outside its package.

To better understand the effects of protected, let’s work through an example. First, change the Book class so that its instance variables are protected, as shown here:

Image

Next, create a subclass of Book, called ExtBook, and a class called ProtectDemo that uses ExtBook. ExtBook ...

Get Java, A Beginner's Guide, 5th Edition, 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.