Using Class Composition to Create a Class From Another
Now we are going to develop one class to deal with
dates and then use this as part of another class to deal with basic
employee information. This is not really an extension, we are
using instances of the data class within our development of the employee
class. This is called class composition.
Now the code for Date.java should be copied into a new directory. // Date.java In order to compile this class and locate it appropriately you need to give the command javac -d c:\jdk1.2.1\jre\classes Date.java This will cause the Date.class to be located along the path C:\jdk1.2.1\jre\classes\edu\quinnipiac\javaProgs\time which can be seen in the following image. |
Now you want to copy the following code into a file called Employee.java in the same directory. I needed to include an import statement that the book didn't have in order to get it to compile. // Employee.java Using the Date class to define birthDate and hireDate is using composition. Now you need to compile this with a similar command to get the class in the appropriate location as shown in the image above. javac -d c:\jdk1.2.1\jre\classes Employee.java Finally we want to test our new class that is partly based on the Date class. Copy the following code into EmployeeTest.java and compile and run this application. You should get some messages in your command window and an appropriate JOptionPane telling you the basic info on Bob Jones. // EmployeeTest.java |