- #1
NightShift
- 7
- 0
Homework Statement
Lab Tasks
1. Change the definition of the lab3.EcoOne class so that it is in a composition
relationship with the example1.Terrarium class. Define a void method named
‘addCaterpillar’ which adds a new example1.Caterpillar to the composed
Terrarium, and starts the Caterpillar. Also define a void method named
‘addButterfly’ which adds a new example1.Butterfly to the composed
Terrarium, and starts the Butterfly.
2. Change the definition of the lab3.EcoTwo class so that it is in two composition
relationships with the example1.Terrarium class. (Hint: this means that there
will be two instance variables of type example1.Terrarium in the lab3.EcoTwo
class.)
Define the methods ‘addCaterpillar’ and ‘addButterfly’ as described above, but
with the following modification. Define these methods so that each time
either method is called, the Terrarium that is added to is swapped. In other
words, if we label the two Terrariums t1 and t2, the first time a Butterfly or a
Caterpillar is added, it is added to t1, but the second time one of them is
added, it is added to t2, and the third time it is added to t1 again, and so on.
For example, the following code must result in two Butterflies and one
Caterpillar in t1, and two Caterpillars in t2:
lab3.EcoTwo et = new lab3.EcoTwo();
et.addButterfly(); added to t1
et.addCaterpillar(); added to t2
et.addCaterpillar(); added to t1
et.addCaterpillar(); added to t2
et.addButterfly(); added to t1
The Attempt at a Solution
Task 1
package lab3;
public class EcoOne {
public example1.Terrarium _et;
public EcoOne() {
_et = new example1.Terrarium();
}
public void addButteryfly(){
example1.Butterfly b;
b = new example1.Butterfly();
_et.add(b);
b.start();
}
public void addCaterpillar(){
example1.Caterpillar c;
c = new example1.Caterpillar();
_et.add(c);
c.start();
}
}
\\This is Part 1 of the Tasks.________________________________________________________________
Task 2package lab3;
public class EcoTwo {
public example1.Terrarium _et;
public void addButterfly(){
example1.Butterfly b;
b = new example1.Butterfly();
_et = temp;
_et.add(b);
temp.add(b);
}
public void addCaterpillar(){
example1.Caterpillar c;
c = new example1.Caterpillar();
_et.add(c);
temp.add(c);
}
public EcoTwo() {
_et = new example1.Terrarium();
lab3.EcoTwo _et2 = new lab3.EcoTwo();
_et.addButterfly();
_et.addCaterpillar();
_et.addCaterpillar();
_et.addCaterpillar();
_et.addButterfly();
}
}
\\This is my attempt on Task 2. I don't know how to complete task 2. My instructor said to declare a temp variable.