O'Reilly logo

Java, A Beginner’s Guide, 5th Edition by Herbert Schildt

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required