The"Has a " Relationship
A Car "has a" Person and an Engine.

Goals

Details

We will create the classes Car, Person, and Engine with this relationship: a Car "has a" Person (owner) and an Engine. For documentation, see the javadocs.


Step Directions DrJava Interactions which should work
1

Create the Engine class

  • See javadocs for more information
> Engine engine = new Engine();
2 Create the Person class
> Person p;
> p.getName()
//should give you a sematic error (what is it called?)

> Person p1 = new Person("jo");
> p1.getName()
"jo"
	  
3 Create just these parts of the Car class:
  • Instance variables
  • Constructor with no argurments
  • "getters"
> Car racer = new Car();
> racer.getOwner()
null
> racer.getEngine()
null
	  
4 In the Car class, create:
  • Methods hasAnOwner() and hasAnEngine()
> Car bug = new Car();
> bug.hasAnOwner()
false
> bug.hasAnEngine()
false	  
	  
5 In the Car class, create:
  • Constructor with two argurments
> Engine engine = new Engine();	  
> Person p1 = new Person("jo");
> Car jeep = new Car(p1, engine);
> jeep.hasAnOwner()
true
> jeep.hasAnEngine()
true
> jeep.getOwner()
// output will vary
> jeep.getOwner().getName()
"jo"
6 In the Car class, create:
  • "setters" setOwner(...) and setEngine(...)

// Same commands from step 5 then add then do the following

> Person p2 = new Person("Candy");

> jeep.setOwner(p2);

> jeep.getOwner().getName() //till here for step 7
"Candy"

//Devise your own test for setEngine(..). May be add some data to Engine class e.g. model number

 

7 Draw the stack and heap memory diagram for the interactions in step 6