Lab 3

advertisement
CS 110 Fall 2007
Lab 3
Lab Objectives
After completing Lab 3, students should be able to



Declare a new class
 Be able to declare fields (instance variables) inside a class
 Be able to write getter methods that return a value
 Be able to write setter methods that take arguments
Be able to instantiate an object
Be able to use calls to instance methods to access and change the state of an object
Lab 3 Assignment
Do Chapter 3, Programming Challenge #1 Employee Class on page 166 of your textbook (this is
on page 179 of the earlier edition of the text).
Employee Class
1. Create a folder for Lab3
2. Inside the Lab3 folder, create a new Java file named Employee.java
a. In Employee.java write a Java class with
i. four fields (instance variables) to hold the name, ID
number, department and position of an employee (see
UML class diagram at right)
b. Write mutator (setter) and accessor (getter) methods for each of
these four fields.
c. Note: to keep it simple, we will use the default constructor
provided with Java for this class
3. Create a new Java file named EmployeeDemo.java to demonstrate your class (driver program)
a. In EmployeeDemo.java write a main method that creates three Employee objects to hold
the data in Table 1
b. Display the data using the getter methods for each employee.
Table 1
Name
ID Number
Department
Position
Susan Meyers
47899
Accounting
Vice President
Mark Jones
39119
IT
Programmer
Joy Rogers
81774
Manufacturing
Engineer
To Receive Credit


If you finish during Thursday's lab, raise your hand to ask the TA to come over, check your
program, and give you credit
If you are unable during Thursday's lab, turn in a printout of your program by the start of class
on Monday.
Page 1 of 2
Starter Java code for Employee.java and EmployeeDemo.java is provided
Employee.java
public class Employee
{
private String name;
private int idNumber;
// 2 more fields needed for department and position
public void setName(String n)
{
name = n;
}
public String getName()
{
return name;
}
//Setters and getters needed for idNumber, department, and position
}
EmployeeDemo.java
public class EmployeeDemo
{
public static void main(String[] args)
{
Employee employee1 = new Employee();
// Create objects for two more employees
// Store data for the first employee.
employee1.setName("Susan Meyers");
employee1.setIdNumber(47899);
employee1.setDepartment("Accounting");
employee1.setPosition("Vice President");
// Store data for the other 2 employees
// Display the data for employee 1.
System.out.println("Employee #1");
System.out.println("Name: " + employee1.getName());
System.out.println("ID Number: " + employee1.getIdNumber());
System.out.println("Department: " + employee1.getDepartment());
System.out.println("Position: " + employee1.getPosition());
System.out.println();
// Display the data for the other two employees
}
}
Page 2 of 2
Download