Karan P. answered 03/28/21
Experienced Python and Java Tutor
Exercise 3.40: The question asks you to create a Tree class, which has only 2 fields - leaves (Triangle class) and trunk (Square class). So first let us build a Tree class and a constructor inside it.
____________________Step 1_________________
class Tree(){
public Tree(){ //This is the constructor
}
}
__________________________________________
Now, we need to declare 2 fields, leaves and trunk, in the Tree class. We will instantiate the 2 variables inside the constructor.
____________________Step 2_________________
class Tree(){
Square trunk;
Triangle leaves;
public Tree(){. //This is the constructor
trunk = new Square(); //object created
leaves = new Triangle(); //object created
}
}
__________________________________________
Now we are done. We did not take any parameters for the constructor.
Exercise 3.41:
NOTE: Since the question does not provide code for the square class. So the names of the square methods are unknown. I have answered how to apply the triangle methods and assumed the names for square methods.
Let us first create a method called setup
____________________Step 1_________________
class Tree(){
Square trunk;
Triangle leaves;
public Tree(){. //This is the constructor
trunk = new Square(); //object created
leaves = new Triangle(); //object created
}
public void setup(){
}
}
__________________________________________
Now, we will use the changeSize method to make the fig leaves look bigger, move their position, and then draw them. Similarly, we only need to display the trunk without changing anything.
We will also call the setup method in the constructor.
____________________Step 2_________________
class Tree(){
Square trunk;
Triangle leaves;
public Tree(){. //This is the constructor
trunk = new Square(); //object created
leaves = new Triangle(); //object created
setup(); // Calling the setup method
}
public void setup(){
leaves.changeSize(125,100); //We will make the fig leaves big
leaves.draw(); // We need to draw them first in order to move them
leaves.moveHorizontal(100); //Please move accordingly to the size and position of trunk
leaves.moveVertical(-150); //Please move accordingly to the size and position of trunk
leaves.makeVisible(); // Lastly this will display the fig leaf
//ASSUMING that trunk's method name is draw and makeVisible
trunk.draw();
trunk.makeVisible();
}
}
__________________________________________
Feel free to ask me any questions if you're still unclear.