Page 574 - Introduction to Programming with Java: A Problem Solving Approach
P. 574
540 Chapter 13 Inheritance and Polymorphism
/**************************************************************
*
Payroll4.java
Dean & Dean
This class hires and pays employees some kind of commission.
**************************************************************/
*
*
*
public class Payroll4
{
public static void main(String[] args)
{
}
// end class PayroAllp4ago PDF Enhancer
but the JVM binds the objects to methods
}
}
// end main
The compiler accepts this cast because Employee2 defines a printPay method,
Commission[] people = new Commission[100];
people[0] = new Commissioned("Glen");
people[1] = new SalariedAndCommissioned("Carol", 24000);
people[0].addSales(15000);
people[1].addSales(15000);
for (int i=0; i<people.length && people[i] != null; i++)
{
((Employee2) people[i]).printPay(15);
Output:
15 Glen: 1500.00
15 Carol: 2500.00
in classes descended from Employee2.
Although you can’t instantiate an interface itself, you can declare interface references.
Figure 13.18 Demonstration of class-like properties of an interface
When should you use the protected modifier? The general rule is that you should use it when you want easy access to a member, but you don’t want to advertise it to the general public. In other words,
6
Suppose you want to enhance the Payroll program so that it includes calculation of FICA taxes (FICA stands for Federal Insurance Contribution Act, and it funds America’s Social Security program). This tax calculation is best done in a separate method. Where should that method go? The only time this calculation will be done is when employees are paid. So, logically, it’s a helper method called by the getpay method.
6 Because a protected member can be accessed from any class descended from the class that defines the protected mem- ber, anyone could extend the class that defines the protected member and thereby gain direct access to it. In other words, the protected modifier doesn’t actuallyprovide much protection. If you’re an outsider, stay away from someone else’s protected members. Consider them to be non-standard products that are not guaranteed.
you want it to have more exposure than a private member, but less exposure than a public member. Hmmm . . . that’s still kind of vague. Let’s elaborate with an example.
Payroll Program with a protected Method