Am I demonstrating composition correctly?
We were given a lab that I'm very confused over the teacher's notes. However I have figured the program out for myself, using my way but not sure if it's actually using composition. "A relationship between classes where an object is a data field within another class." is what we were told.
Our assignment was this:
Code :
Define a Date Class that will be used for containment.
Attributes: month, day, year.
Valid values: month 1-12, day 1-30, year 1900-2012.
Define an Employee Class that will be used as a container.
Attributes: name, birthDate, hireDate.
Define methods to ensure ownership of contained objects.
Demonstrate Composition.
Here is my code.
Code :
public class CompositionDemo{
public static void main(String[] args){
Date b = new Date(03,17,1987);
Date h = new Date(05,20,2003);
Employee joe = new Employee("Joe",b,h);
System.out.println("Name: " + joe.getName());
System.out.println("Hire date: " + joe.getHireDate());
System.out.println("Birth date: " + joe.getBirthDate());
}
}
Code :
//contained class
public class Date{
private int month;
private int day;
private int year;
public Date(int m, int d, int y){
month = m;
day = d;
year = y;
}
}
Code :
//containing class
public class Employee{
private String name;
private Date birthDate;
private Date hireDate;
public Employee(String nm, Date bD, Date hD){
name = nm;
birthDate = bD;
hireDate = hD;
}
public Date getHireDate(){
return this.hireDate;
}
public Date getBirthDate(){
return this.birthDate;
}
public String getName(){
return this.name;
}
}
Does this truly display composition correctly, or am I misunderstanding the concept? The reason I ask is because when I follow his notes he wants the Date and Employee class to look something like this....
Code :
public class Employee{
private String name;
private Date birthDate;
private Date hireDate;
public Employee(String n, Date bD, Date hD){
name = new String(n);
birthDate = bD.copy();
hireDate = hD.copy();
}
public Date getHireDate(){
return this.hireDate.getDate();
}
}
Code :
public class Date{
private int month;
private int day;
private int year;
public Date(Date d){
this.month = d.month;
this.day = d.day;
this.year = d.year;
}
public Date copy(){
return new Date(this);
}
public Date getDate(){
return this.copy();
}
}
So, honestly I have no clue how to use his example to demonstrate, because it seems like a paradox where it wants a date object in the date constructor but in order to create a Date object you need a date object already!!!?!?! It confuses me pretty bad. Looking for any and all help whether my way was correct and some tips to better understand composition. Thanks!