Java Reference
In-Depth Information
LISTING 9.2
//********************************************************************
// Book.java Author: Lewis/Loftus
//
// Represents a book. Used as the parent of a derived class to
// demonstrate inheritance.
//********************************************************************
public class Book
{
protected int pages = 1500;
//----------------------------------------------------------------
// Pages mutator.
//----------------------------------------------------------------
public void setPages ( int numPages)
{
pages = numPages;
}
//----------------------------------------------------------------
// Pages accessor.
//----------------------------------------------------------------
public int getPages ()
{
return pages;
}
}
The protected Modifier
As we've seen, visibility modifiers are used to control access to the members of
a class. This effect extends into the process of inheritance as well. Any public
method or variable in a parent class can be explicitly referenced by name in the
child class and through objects of that child class. On the other hand, private
methods and variables of the parent class cannot be referenced in the child class
or through an object of the child class.
However, if we declare a variable with public visibility so that a derived
class can reference it, we violate the principle of encapsulation. Therefore, Java
provides a third visibility modifier: protected . Note that the variable pages is
declared with protected visibility in the Book class. When a variable or method is
 
Search WWH ::




Custom Search