Java Reference
In-Depth Information
this.make = make;
this.model = model;
//partNumber = 11223344L; //Does not compile
}
private void setRetailPrice(double p)
{
//System.out.println(getPartNumber()); //Does not compile
retailPrice = p;
}
}
In the DVDPlayer class, the commented-out statement that follows does not
compile because partNumber is private in the parent. A DVDPlayer object gets
a field named partNumber of type long in memory, but the DVDPlayer class
does not have access to partNumber because it is private. The only place part-
Number can be accessed is within the InventoryItem class.
partNumber = 11223344L;
Similarly, the attempt to invoke getPartNumber() fails in the statement:
System.out.println(getPartNumber());
The getPartNumber() method has default access and is only accessible from
classes in the products package. The DVDPlayer class is in the electronics
package and therefore cannot invoke getPartNumber().
The InventoryItem class has a protected constructor. Only classes in the
products package or that subclass InventoryItem can access this constructor.
The child class DVDPlayer invokes the protected constructor in InventoryItem
with the statement:
super();
This is allowed because DVDPlayer is a child of InventoryItem. In the fol-
lowing AccessDemo program, an attempt is made to use the protected Inven-
toryItem constructor with the statement:
InventoryItem x = new InventoryItem();
This statement in AccessDemo does not compile because the AccessDemo
class is not a subclass of InventoryItem, nor is it in the products package.
The AccessDemo program attempts to instantiate and use objects of type
InventoryItem and DVDPlayer. The AccessDemo class is in a different package
than both classes and does not extend either class; therefore, AccessDemo only
has access to the public members of both classes.
Search WWH ::




Custom Search