Replace each error print statement below in with a thrown exception statement. M
ID: 3784745 • Letter: R
Question
Replace each error print statement below in with a thrown exception statement. Modify each class below that contains an error print statement and replace it with a thrown exception.
Figure 10.5: SalariedEmployee.java
2 // SalariedEmployee class extends Employee.
3
4 public class SalariedEmployee extends Employee
5 {
6 private double weeklySalary;
7
8 // four-argument constructor
9 public SalariedEmployee( String first, String last, String ssn,
10 double salary )
11 {
12 super( first, last, ssn ); // pass to Employee constructor
13 setWeeklySalary( salary ); // validate and store salary
14 } // end four-argument SalariedEmployee constructor
15
16 // set salary
17 public void setWeeklySalary( double salary )
18 {
19 weeklySalary = salary < 0.0 ? 0.0 : salary;
20 } // end method setWeeklySalary
21
22 // return salary
23 public double getWeeklySalary()
24 {
25 return weeklySalary;
26 } // end method getWeeklySalary
27
28 // calculate earnings; override abstract method earnings
// in Employee
29 public double earnings()
30 {
31 return getWeeklySalary();
32 } // end method earnings
33
34 // return String representation of SalariedEmployee object
35 public String toString()
36 {
37 return String.format( "salaried employee: %s %s: $%,.2f",
38 super.toString(), "weekly salary", getWeeklySalary() );
39 } // end method toString
40 } // end class SalariedEmployee
Explanation / Answer
Hi,
I have modified the code and highlighted the code changes below.
SalariedEmployee.java
public class SalariedEmployee extends Employee
{
private double weeklySalary;
// constructor
public SalariedEmployee(String first, String last,
String ssn, double salary)
{
super(first, last, ssn);
setWeeklySalary(salary);
}
// set salary
public void setWeeklySalary(double weeklySalary)
{
if (weeklySalary < 0.0)
throw new IllegalArgumentException(
"Weekly salary must be >= 0.0");
this.weeklySalary = weeklySalary;
}
// return salary
public double getWeeklySalary()
{
return weeklySalary;
}
// calculate earnings; override abstract method earnings in Employee
@Override
public double earnings()
{
return getWeeklySalary();
}
// return String representation of SalariedEmployee object
@Override
public String toString()
{
return String.format("salaried employee: %s%n%s: $%,.2f",
super.toString(), "weekly salary", getWeeklySalary());
}
}