Composition

A class doesn’t just need to contain methods and variables, it can also contain references to object. This is known as composition.

Any time you want to turn an object into a string, we go to that class, and call the toString method

// jamesprogram.java
class jamesprogram {

	public static void main (String[] args){
		
		cat catObject = new cat(5,6,7);
		
		dog dogObject = new dog("oliver",catObject);
		
		System.out.println(dogObject);

	}
}
//cat.java
public class cat {
	
	// 3 private variables
	private int month;
	private int day;
	private int year;
	
	// constructor
	public cat(int m, int d, int y){
		month=m;
		day=d;
		year=y;
		
		// the reference 'this' below is a reference
		// to whatever object we just built
		System.out.printf("The contructor for this is %s\n", this);
	}
	
	public String toString(){
		return String.format("%d/%d/%d", month, day, year);
	}
	
}
//dog.java
public class dog {

		private String name;
		private cat birthday; // this bit is composition
		
		// this constructor takes a name
		// and an object
		public dog(String theName, cat theDate){
			name = theName;
			// this is a reference to theDate object
			birthday = theDate; 
		}
		
		public String toString(){
			return String.format("My name is %s, my birthday is %s", name, birthday);
		}
}

This program outputs:

The contructor for this is 5/6/7
My name is oliver, my birthday is 5/6/7

Leave a Reply