Project 6 Inheritance and File I/O Introduction The purpose of this project is t
ID: 3766214 • Letter: P
Question
Project 6
Inheritance and File I/O
Introduction
The purpose of this project is to learn about inheritance, one of the pillars of the java language.
In this project the student will design a base class Employee and then extend that class for two different types of Employee: Technician and Salesman. See the file Employee.java associated with this project.
Various types of base Employee and extended class Technicians and SalesMan will be put into an array. When printing out the array you will see how java determines class type at run time a very useful property.
You will learn the rules of overriding base class methods and constructors.
You will also learn to use file i/o methods to write text and objects to a files, and read text and objects back from files with error handling mechanisms.
Procedure
Class descriptions
1. Employee see the starting code for Employee in this directory.
Implement Comparable and add a compareTo() method.
Implement Serializable.
Add toString() to display information.
2. SalesMan extends Employee
private double for sales target in dollars
private String for territory
default constructor - What will you use the default constructor for?
4 parameter constructor which uses super(param1, param2)
toString() method to display all SalesMan information. You will need to call super.toString()
Getters and setters as necessary.
3. Technician extends Employee
private integer for level as in 1, 2, 3
private String for department as in production, quality control, field service
default constructor and 4 parameter constructor which uses super( param1, param2)
toString() method to display all Technician information. You will need to call super.toString()
Getters and setters as necessary.
4. FileIO
Will contain static methods. You can use this class for all kinds of future programming tasks.
Note: you will use the file I/O methods discussed in class or in the textbook.
method 1:writeAsText() receives an array of employees and a file name.
It writes the individual employee (salesman or technician) info as text to a file which can be read by humans. This is the reverse of method 2. See text file format below. See part 2 of UseCompany.
method 2: loadArray() takes a text file name, reads it for Technician or Salesman parameters, instantiates the correct type of employee and adds it to an array of Employees.
No use of the tokenizer class!
It returns the array of employees. This is the reverse of method 1. See text file format below. See part 5 of UseCompany.
method 3:writeObject() takes an array of employees and a file name.
It writes the whole array as a single object to a file (which cannot be read by humans). This is the reverse of method 4. See part 3 of UseCompany.
method 4: readObject() takes a file name, reads an array object from the file and returns it as an array. This is the reverse of method 3. See part 4 of UseCompany.
method 5: displayArray() receives an array of employees .
It displays the contents of the array as one employee per line.
5. UseCompany
This contains the code for testing. Proceed as follows..
1. Create 2 Employees (one technican, one salesperson) using default constructor. Add to an array called myCompany.
Create 2 technicians and 2 salesmen using the 4 parameter constructors and add to the Array.
Sort this array.
Display it. Was the correct info printed out ?
2. Write the Array as text to a file, one employee at a time. Print the actual contents of the file containing the array. Comment
3. Write the Array as an object to a file. Print the actual contents of the file containing the objects. Comment on what you see.
4. Read the object file back into a new array.
Display it. Was the correct info printed out? (i.e. same as original display).
5. a) Read the text file written in part 2 above into an array.
Display it. Was the correct info printed out? (i.e. same as original display).
b) Prepare by hand, a text file of 3-6 employees. See the text file format below. Read the file into an array, display it and confirm it matches the data entered.
6. Text file format
The text file will be 1 line, comma separated per employee.
For a Technician : T,String,int,int,String, for the appropriate fields.
For a Salesman : S,String,int,double,String, for the appropriate fields.
For example: T,Fred,014,1,Shipping,
---------------------------------------------------------------------------------------------------------------------------------------------------------------
Explanation / Answer
As we have used them so far, array are primarily variables. This means that an array can be declared as a field in a class. To create a field as an array, you can declare it like a normal array in the body of the class. Here is an example:
public class CoordinateSystem {
private int[] Points;
}
Like any field, when an array has been declared as a member variable, it is made available to all the other members of the same class. You can use this feature to initialize the array in one method and let other methods use the initialized variable. This also means that you do not have to pass the array as argument nor do you have to explicitly return it from a method.
After or when declaring an array, you must make sure you allocate memory for it prior to using it. Unlike C++, you can allocate memory for an array when declaring it. Here is an example:
public class CoordinateSystem {
private int[] Points = new int[4];
}
You can also allocate memory for an array field in a constructor of the class. Here is an example:
public class CoordinateSystem {
private int[] Points;
public CoordinateSystem() {
Points = new int[4];
}
}
If you plan to use the array as soon as the program is running, you can initialize it using a constructor or a method that you know would be called before the array can be used. Here is an example:
public class CoordinateSystem {
private int[] Points;
public CoordinateSystem() {
Points = new int[4];
Points[0] = 2;
Points[1] = 5;
Points[2] = 2;
Points[3] = 8;
}
}
Practical Learning: Introducing Arrays and Classes
package rentalproperties1;
enum PropertyType {
SINGLEFAMILY,
TOWNHOUSE,
APARTMENT,
UNKNOWN };
public class RentalProperty {
private long[] propertyNumbers;
private PropertyType[] types;
private short[] bedrooms;
private float[] bathrooms;
private double[] monthlyRent;
public RentalProperty() {
propertyNumbers = new long[] {
192873, 498730, 218502, 612739,
457834, 927439, 570520, 734059 };
types = new PropertyType[] {
PropertyType.SINGLEFAMILY, PropertyType.SINGLEFAMILY,
PropertyType.APARTMENT, PropertyType.APARTMENT,
PropertyType.TOWNHOUSE, PropertyType.APARTMENT,
PropertyType.APARTMENT, PropertyType.TOWNHOUSE };
bedrooms = new short[] { 5, 4, 2, 1, 3, 1, 3, 4 };
bathrooms = new float[] { 3.50F, 2.50F, 1.00F, 1.00F,
2.50F, 1.00F, 2.00F, 1.50F };
monthlyRent = new double[] {
2250.00D, 1885.00D, 1175.50D, 945.00D,
1750.50D, 1100.00D, 1245.95D, 1950.25D };
}
}
Presenting the Array
After an array has been created as a field, it can be used by any other member of the same class. Based on this, you can use a member of the same class to request values that would initialize it. You can also use another method to explore the array. Here is an example:
class CoordinateSystem {
private int[] Points;
public CoordinateSystem() {
Points = new int[4];
Points[0] = 2;
Points[1] = -5;
Points[2] = 2;
Points[3] = 8;
}
public void showPoints() {
System.out.println("Points Coordinates");
System.out.println("P(" + Points[0] + ", " + Points[1] + ")");
System.out.println("Q(" + Points[2] + ", " + Points[3] + ")");
}
}
public class Exercise {
public static void main(String[] args) throws Exception {
CoordinateSystem coordinates = new CoordinateSystem();
coordinates.showPoints();
}
}
This would produce:
Points Coordinates
P(2, -5)
Q(2, 8)
Practical Learning: Presenting an Array
package rentalproperties1;
enum PropertyType {
SINGLEFAMILY,
TOWNHOUSE,
APARTMENT,
UNKNOWN
};
public class RentalProperty {
private long[] propertyNumbers;
private PropertyType[] types;
private short[] bedrooms;
private float[] bathrooms;
private double[] monthlyRent;
public RentalProperty() {
propertyNumbers = new long[] {
192873, 498730, 218502, 612739,
457834, 927439, 570520, 734059 };
types = new PropertyType[] {
PropertyType.SINGLEFAMILY, PropertyType.SINGLEFAMILY,
PropertyType.APARTMENT, PropertyType.APARTMENT,
PropertyType.TOWNHOUSE, PropertyType.APARTMENT,
PropertyType.APARTMENT, PropertyType.TOWNHOUSE };
bedrooms = new short[] { 5, 4, 2, 1, 3, 1, 3, 4 };
bathrooms = new float[] { 3.50F, 2.50F, 1.00F, 1.00F,
2.50F, 1.00F, 2.00F, 1.50F };
monthlyRent = new double[] {
2250.00D, 1885.00D, 1175.50D, 945.00D,
1750.50D, 1100.00D, 1245.95D, 1950.25D };
}
public void showListing() {
System.out.println("Properties Listing");
System.out.println("=============================================");
System.out.println("Prop # Property Type Beds Baths Monthly Rent");
System.out.println("---------------------------------------------");
for (int i = 0; i < 8; i++) {
System.out.printf("%d %s %d %.2f %.2f ",
propertyNumbers[i], types[i], bedrooms[i],
bathrooms[i], monthlyRent[i]);
}
System.out.println("=============================================");
}
}
package rentalproperties1;
public class Main {
public static void main(String[] args) throws Exception {
RentalProperty property = new RentalProperty();
property.showListing();
}
}
Properties Listing
=============================================
Prop # Property Type Beds Baths Monthly Rent
---------------------------------------------
192873 SINGLEFAMILY 5 3.50 2250.00
498730 SINGLEFAMILY 4 2.50 1885.00
218502 APARTMENT 2 1.00 1175.50
612739 APARTMENT 1 1.00 945.00
457834 TOWNHOUSE 3 2.50 1750.50
927439 APARTMENT 1 1.00 1100.00
570520 APARTMENT 3 2.00 1245.95
734059 TOWNHOUSE 4 1.50 1950.25
=============================================
Arrays and Methods
Introduction
Each member of an array holds a legitimate value. Therefore, you can pass a single member of an array as argument. You can pass the name of the array variable with the accompanying index to a method.
The main purpose of using an array is to have access to various values grouped under one name. Still, an array is primarily a variable. As such, it can be passed to a method and it can be returned from a method.
Returning an Array From a Method
Like a normal variable, an array can be returned from a method. This means that the method would return a variable that carries various values. When declaring or defining the method, you must specify its data type. When the method ends, it would return an array represented by the name of its variable.
You can create a method that takes an array as argument and returns another array as argument.
To declare a method that returns an array, on the left of the method's name, provide the type of value that the returned array will be made of, followed by empty square brackets. Here is an example:
public class CoordinateSystem {
public int[] Initialize() {
}
}
Remember that a method must always return an appropriate value depending on how it was declared. In this case, if it was specified as returning an array, then make sure it returns an array and not a regular value. One way you can do this is to declare and possibly initialize a local array variable. After using the local array, you return only its name (without the square brackets). Here is an example:
class CoordinateSystem {
public int[] Initialize() {
int[] Coords = new int[] { 12, 5, -2, -2 };
return Coords;
}
}
When a method returns an array, that method can be assigned to an array declared locally when you want to use it. Remember to initialize a variable with such a method only if the variable is an array.
Here is an example:
class CoordinateSystem {
public int[] Initialize() {
int[] Coords = new int[] { 12, 5, -2, -2 };
return Coords;
}
}
public class Exercise {
public static void main(String[] args) throws Exception {
int[] System = new int[4];
CoordinateSystem coordinates = new CoordinateSystem();
System = coordinates.Initialize();
}
}
The method could also be called as follows:
class CoordinateSystem {
public int[] Initialize() {
int[] Coords = new int[] { 12, 5, -2, -2 };
return Coords;
}
}
public class Exercise {
public static void main(String[] args) throws Exception {
CoordinateSystem coordinates = new CoordinateSystem();
int[] System = coordinates.Initialize();
}
}
If you initialize an array variable with a method that does not return an array, you would receive an error.
An Array Passed as Argument
Like a regular variable, an array can be passed as argument. To do this, in the parentheses of a method, provide the data type, the empty square brackets, and the name of the argument. Here is an example:
public class CoordinateSystem {
public void showPoints(int[] Points) {
}
}
When an array has been passed to a method, it can be used in the body of the method as any array can be, following the rules of array variables. For example, you can display its values. The simplest way you can use an array is to display the values of its members. This could be done as follows:
public class CoordinateSystem {
public void showPoints(int[] Points) {
System.out.println("Points Coordinates");
System.out.println("P(" + Points[0] + ", " + Points[1] + ")");
System.out.println("Q(" + Points[2] + ", " + Points[3] + ")");
}
}
To call a method that takes an array as argument, simply type the name of the array in the parentheses of the called method. Here is an example:
class CoordinateSystem {
public void showPoints(int[] Points) {
System.out.println("Points Coordinates");
System.out.println("P(" + Points[0] + ", " + Points[1] + ")");
System.out.println("Q(" + Points[2] + ", " + Points[3] + ")");
}
}
public class Exercise {
public static void main(String[] args) throws Exception {
int Points[] = new int[] { -3, 3, 6, 3 };
CoordinateSystem coordinates = new CoordinateSystem();
coordinates.showPoints(Points);
}
}
This would produce:
Points Coordinates
P(-3, 3)
Q(6, 3)
When an array is passed as argument to a method, the array is passed by reference. This means that, if the method makes any change to the array, the change would be kept when the method exits. You can use this characteristic to initialize an array from a method. Here is an example:
class CoordinateSystem {
public void initialize(int[] coords) {
coords[0] = -4;
coords[1] = -2;
coords[2] = -6;
coords[3] = 3;
}
public void showPoints(int[] Points) {
System.out.println("Points Coordinates");
System.out.println("P(" + Points[0] + ", " + Points[1] + ")");
System.out.println("Q(" + Points[2] + ", " + Points[3] + ")");
}
}
public class Exercise {
public static void main(String[] args) throws Exception {
int system[] = new int[4];
CoordinateSystem coordinates = new CoordinateSystem();
coordinates.initialize(system);
coordinates.showPoints(system);
}
}
This would produce:
Points Coordinates
P(-4, -2)
Q(-6, 3)
Notice that the initialize() method receives an un-initialized array but returns it with new values.
Instead of just one, you can create a method that receives more than one array and you can create a method that receives a combination of one or more arrays and one or more regular arguments. There is no rule that sets some restrictions.
You can also create a method that takes one or more arrays as argument(s) and returns a regular value of a primitive type.
The main() Method
Introduction
When a program starts, it looks for an entry point. This is the role of the main() method. In fact, a program, that is, an executable program, starts by, and stops with, the main() method. The way this works is that, at the beginning, the compiler looks for a method called main. If it does not find it, it produces an error. If it finds it, it enters the main() method in a top-down approach, starting just after the opening curly bracket. If it finds a problem and judges that it is not worth continuing, it stops and lets you know. If, or as long as, it does not find a problem, it continues line after line, with the option to even call or execute a method in the same file or in another file. This process continues to the closing curly bracket "}". Once the compiler finds the closing bracket, the whole program has ended and stops.
If you want the user to provide information when executing your program, you can take care of this in the main() method. Consider the following code written in a file saved as Exercise.java:
public class Exercise {
public static void main(String[] args) throws Exception {
String firstName = "James";
String lastName = "Weinberg";
double weeklyHours = 36.50;
double hourlySalary = 12.58;
String fullName = lastName + ", " + firstName;
double weeklySalary = weeklyHours * hourlySalary;
System.out.println("Employee Payroll");
System.out.printf("Full Name: %s ", fullName);
System.out.printf("WeeklySalary: %.2f", weeklySalary);
}
}
To execute the application, at the Command Prompt and after Changing to the Directory that contains the file, you would type
C:Exercise>javac Exercise.java
and press Enter. To execute the program, you would type the name Java Exercise and press Enter. The program would then prompt you for the information it needs.
Command Request from main()
To compile a program, at the command prompt, you would type javac, followed by the name of the file that contains main(), followed by the .java extension. Then, to execute a program, you would type the java command, followed by the name of the file. If you distribute a program, you would tell the user to type java followed by the name of the program at the command prompt. In some cases, you may want the user to type additional information besides the name of the program. To request additional information from the user, you can pass a String argument to themain() method. The argument should be passed as an array and make sure you provide a name for the argument. Here is an example:
public class Exercise {
public static void main(String[] args) throws Exception {
}
}
The reason you pass the argument as an array is so you can use as many values as you judge necessary. To provide values at the command prompt, the user types the name of the program followed by each necessary value. Here is an example:
The values the user would provide are stored in a zero-based array without considering the name of the program. The first value (that is, after the name of the program) is stored at index 0, the second at index 1, etc. Based on this, the first argument is represented by args[0], the second is represented by args[1], etc.
Each of the values the user types is a string. If any one of them is not a string, you should convert/cast its string first to the appropriate value. Consider the following source code:
import java.io.*;
public class Exercise {
public static void main(String[] args) throws Exception {
String firstName;
String lastName;
double weeklyHours;
double hourlySalary;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
firstName = args[0];
lastName = args[1];
weeklyHours = Double.parseDouble(args[2]);
hourlySalary = Double.parseDouble(args[3]);
String fullName = lastName + ", " + firstName;
double weeklySalary = weeklyHours * hourlySalary;
System.out.println("Employee Payroll");
System.out.printf("Full Name: %s ", fullName);
System.out.printf("Weekly Salary: %.2f ", weeklySalary);
}
}
As we have used them so far, array are primarily variables. This means that an array can be declared as a field in a class. To create a field as an array, you can declare it like a normal array in the body of the class. Here is an example:
public class CoordinateSystem {
private int[] Points;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.