Page 573 - Introduction to Programming with Java: A Problem Solving Approach
P. 573
13.10 The protected Access Modifier 539 Employee2 class. Note that we need an extra set of parentheses surrounding the (Commission) cast op-
erator and the calling object. We could have used more specific casts like this:
((Commissioned) employees[3]).addSales(15000);
((SalariedAndCommissioned) employees[4]).addSales(15000);
But it’s more elegant to cast into the more generic Commission interface type and let the JVM select among the polymorphic alternatives as it does its dynamic binding. Using either type of casting, here’s what the Payroll3 driver generates:
Output:
4 Anna: 800.00
4 Donovan: 640.00
11 Anna: 1000.00
11 Donovan: 800.00
15 Simon: 2000.00
15 Glen: 1500.00
15 Carol: 2500.00
In our coded examples, notice the similarity between the use of an interface name and the use of a class name! It’s not possible to instantiate an interface because it’s inherently abstract, but you can use it like any ordinary class to specify type. For example, you can declare an array of elements whose type is an interface name, you can populate that array with instances of classes that implement that inter- face, and then you can pull objects out of that array and cast them into any type (class or interface) that those objects conform to.ATpheaPagyroll4 dPrivDerFin FiEgunre h13a.18nancd ethersubsequent output illustrate these possibilities.
The trick is to think about what the compiler needs and what the JVM does. For example, you can cre- ate an array of interface references because the elements in the array are just references, not instantiated objects. The compiler lets you populate that array with references to objects from classes that implement that interface because it knows those objects can call any method the interface declares. In a method call, the compiler lets you cast a reference into the type of any class that declares or defines any version of that method because it knows the JVM can find at least one method to bind. At runtime, the JVM selects the most appropriate method to bind.
13.10 The protected Access Modifier
So far, we’ve discussed only two modes of accessibility for a class’s members—public and private; public members can be accessed from anywhere; private members can be accessed only from inside the members’ class. There is another access modifier that is a limited form of the public access modi- fier—the protected access modifier. It specifies an accessibility that’s between public and private. Members that are protected can be accessed only from within the same package5 or from within the member’s subtree. What’s a subtree? It’s a class hierarchy that consists of a class plus all of its descendant classes.
5 If you want to learn more about packages and how to group your classes into a programmer-defined package, see Appendix 4.