Today, for the first time, we took a close look at classes. In particular, we saw how to create a new type using instance variables and methods.
Example 1. Create an Employee class with minimal features (name, hours worked, and pay rate). Write a program that uses the new Employee class.
//File: Employee.java
import CSLib.*;
public class Employee
{
//Attributes (data) of Employee - Instance Variables
String firstName,
lastName;
double
hoursWorked,
payRate;
//Behavior (operations) of Employee- Instance Methods
//Accessor Methods. They merely access the private data fields.
double salary ()
{
if (hoursWorked < 40)
{
return
payRate * hoursWorked;
}
else
{
return
payRate * 40 + 1.5 * payRate * (hoursWorked - 40);
}
}
String getName()
{
return firstName + "
" + lastName;
}
//Mutator Methods. They change or update the private data fields:
// firstName, lastName,
hoursWorked, and payRate.
void setName()
{
InputBox in = new InputBox();
in.setPrompt ("First name please: ");
firstName = in.readString();
in.setPrompt ("Last name please: ");
lastName = in.readString();
}
void setHoursWorked()
{
InputBox in = new InputBox();
in.setPrompt ("How many hours did you work
last week? ");
hoursWorked = in.readDouble();
}
void setPayRate()
{
InputBox in = new InputBox();
in.setPrompt ("What is your hourly pay
rate? ");
payRate = in.readDouble();
}
}
This class must be compiled (>javac Employee.java) just like any other Java source
code. However, it cannot be run (>java Employee) since it has no main() method.
In order to use the Employee class (or type), we must write a client program (with
a main()).
//File: EmployeeClient.java
import CSLib.*;
public class EmployeeClient
{
public static void main (String [] args)
{
//Create a new person object
Employee person = new
Employee();
//define the attributes of person
person.setName();
person.setHoursWorked();
person.setPayRate();
//output the attributes of person
OutputBox out = new
OutputBox();
out.setSize(550, 75);
out.println (person.getName() + " worked
" + person.hoursWorked
+ " hours at $ " + person.payRate
+ " per hour and earned $ " + person.salary()
+ ".");
}
}



Example 2. Add protection to the data fields (attributes) of the Employee class.
//File: Employee2.java
import CSLib.*;
/**
* This class represents <B>Employees</B>
* @author Bill Steinmetz
*/
public class Employee2
{
//Attributes
private String firstName,
lastName;
private double hoursWorked,
payRate,
salary;
//Accessor methods
//The toString() method allows direct output of an Employee object
//through System.out.print(employee)
/**
* @return a <code>String</code>
representing all of
* the Employee's data
*/
public String toString()
{
return firstName + "
" + lastName + " worked " + hoursWorked
+ " hours at $ " + payRate + " per hour and earned $ "
+ salary + ".";
}
/**
* @return a <code>String</code>
representing the Employee's full name
*/
public String getName()
{
return firstName + "
" + lastName;
}
//Mutator methods
/**
* Calculates the Employee's salary including time
worked
* beyond 40 hours per week (overtime)
*/
public void calculateSalary ()
{
if (hoursWorked < 40)
{
salary = payRate *
hoursWorked;
}
else
{
salary = payRate * 40 +
1.5 * payRate * (hoursWorked - 40);
}
}
/**
* Interactively assigns the Employee's first and last
names
*/
void setName()
{
InputBox in = new InputBox();
in.setPrompt ("First name please: ");
firstName = in.readString();
in.setPrompt ("Last name please: ");
lastName = in.readString();
}
/**
* Interactively assigns the number of hours worked
*/
void setHoursWorked()
{
InputBox in = new InputBox();
in.setPrompt ("How many hours did you work
last week? ");
hoursWorked = in.readDouble();
}
/**
* Interactively assigns the Employee's rate of pay
*/
void setPayRate()
{
InputBox in = new InputBox();
in.setPrompt ("What is your hourly pay
rate? ");
payRate = in.readDouble();
}
If you would apply the EmployeeClient.java program to an Employee2 object, you would generate the following error messages:
EmployeeDriver.java:16: Variable hoursWorked in class Employee2 not
accessible from class EmployeeDriver.
System.out.println (person.fullName() + " worked " + person.hoursWorked
^
EmployeeDriver.java:17: Variable payRate in class Employee2 not accessible from class
EmployeeDriver.
+ " hours at $ " + person.payRate + " and earned $"
^
Since hoursWorked and payRate are private variables, they are accessible ONLY from within the Employee class. Instead, we'll use a new program to test our new Employee2 class. By contrast, the methods (or behavior) of the Employee class are public, which gives access to any class outside the Employee class.
//File: Employee2Client.java
import CSLib.*;
public class Employee2Client
{
public static void main (String [] args)
{
//Create a new Employee2 object with null
or 0 attributes
Employee2 person = new
Employee2();
person.setName();
person.setHoursWorked();
person.setPayRate();
person.calculateSalary();
//output the attributes of person
OutputBox out = new
OutputBox();
out.setSize(550, 75);
out.println (person.toString());
}
}
Finally, it is sometimes useful to be able to construct objects with predetermined attributes. This is accomplished by explicitely adding constructors to the class.
Example 3. Add additional constructor to Employee class.
//File: Employee3.java
import CSLib.*;
/**
* This class represents <B>Employees</B>
* @author Bill Steinmetz
*/
public class Employee3
{
private String firstName,
lastName;
private double hoursWorked,
payRate,
salary;
//Overloaded constructors
/**
* Employee3 default constructor initializes each
* instance variable to null (Strings) or 0 (doubles)
*/
public Employee3 ()
{}
/**
* Employee3 constructor
* @param f firstName
* @param l lastName
* @param h hoursWorked
* @param p payRate
*/
public Employee3 (String f, String l, double
h, double p)
{
firstName = f;
lastName = l;
hoursWorked = h;
payRate = p;
}
//Accessor methods
/**
* @return a <code>String</code>
representing all of
* the Employee's data
*/
public String toString()
{
return firstName + "
" + lastName + " worked " + hoursWorked
+ " hours at $ " + payRate + " per hour and earned $ "
+ salary + ".";
}
/**
* @return a <code>String</code>
representing the Employee's full name
*/
public String getName()
{
return firstName + "
" + lastName;
}
//Mutator Methods
/**
* Calculates the Employee's salary including time
worked
* beyond 40 hours per week (overtime)
*/
public void calculateSalary ()
{
if (hoursWorked < 40)
{
salary = payRate *
hoursWorked;
}
else
{
salary = payRate * 40 +
1.5 * payRate * (hoursWorked - 40);
}
}
/**
* Interactively assigns the Employee's first and last
names
*/
void setName()
{
InputBox in = new InputBox();
in.setPrompt ("First name please: ");
firstName = in.readString();
in.setPrompt ("Last name please: ");
lastName = in.readString();
}
/**
* Interactively assigns the number of hours worked
*/
void setHoursWorked()
{
InputBox in = new InputBox();
in.setPrompt ("How many hours did you work
last week? ");
hoursWorked = in.readDouble();
}
/**
* Interactively assigns the Employee's rate of pay
*/
void setPayRate()
{
InputBox in = new InputBox();
in.setPrompt ("What is your hourly pay
rate? ");
payRate = in.readDouble();
}
}
An example of a client program (a program that uses the Employee3 class) is:
//File: Employee3Client.java
import CSLib.*;
public class Employee3Client
{
public static void main (String [] args)
{
//Create 2 employees, person1, who is created,
but not initialized
//and person2, who is created and initialized
through the copy
//constructor
Employee3 person1 = new
Employee3 ();
Employee3 person2 = new
Employee3 ("Bill", "Steinmetz", 50, 5);
//Set attributes of person1
person1.setName();
person1.setHoursWorked();
person1.setPayRate();
person1.calculateSalary();
//Calculate person2's salary
person2.calculateSalary();
//output person1 and person2 attributes
OutputBox out = new
OutputBox();
out.setSize(550, 75);
out.println (person1.toString());
out.println (person2.toString());
}
}
This last version (Employee3) is the most flexible of the three, providing both the safety
of explicit access modifiers (private and public) as well overloaded constructors.
SPECIAL NOTE: Constructors look just like any other method except for 2 things:
The name of the method is exactly the same as the name of the class.
Constructors MUST NOT return a value.
Take a close look at the Employee3() constructors and you'll see that they conform to these two rules.
NOTE: We have begun to use the "javadoc" documentation comments. They begin with /** and end with */. The javadoc program has its own set of "tags" that begin with the @ symbol. Once inserted into your code, you can generate your own javadoc documentation (HTML) with the command line:
>javadoc program.java -d yourDirectory -author
Once generated, go to that directory and click on the index.html file to see the results. To see the Employee2 and Employee3 documentation, just click on the links.
Lab Exercise. Add a method to the Employee class, say
public void payRaise (double raise)
that gives the employee a pay raise of raise percent. NOTE: This method should just change the payRate field to reflect the raise. There is no need to create another data field. If you want to see my solution to this problem, just click on Employee4.java and Employee4Client.java.