Many of the FRQs on the AP exam contain a table which shows output or return values from methods in a class. In these practice exercises, you will be given a table that shows method calls and their output. You will need to write a class with the described methods that will produce the output shown in the table. Thank you to Sam Procopio from Bishop Blanchet High School in Seattle, WA, for these exercises.
Subsection3.16.1Tree Class
Write a class called Tree that has the appropriate instance variables and methods to produce the output described in the table below.
Table3.16.1.
Method Calls
Output
Tree birch = new Tree(10, “soft”);
System.out.println(birch.getHeight());
10
birch.water(5);
System.out.println(birch.getHeight());
15
birch.cut();
System.out.println(birch.getHeight());
7
System.out.println(birch.woodType());
soft wood
Tree oak = new Tree(20, “hard”);
System.out.println(oak.getHeight());
20
System.out.println(oak.woodType());
hard wood
oak.water(2);
System.out.println(oak.getHeight());
22
oak.cut();
System.out.println(oak.getHeight());
14
Activity3.16.1.
Write the class Tree below with the appropriate instance variables, constructor, and methods described in main method and in the table above.
Subsection3.16.2Book Class
Based on the table below, write a complete class called Book that has the appropriate instance variables and methods to produce the output described in the table.
Table3.16.2.
Method Calls
Output
Book hp = new Book(“Harry Potter”, 150, true);
System.out.println(hp.getNumPages());
150
System.out.println(hp.getName());
Harry Potter
System.out.println(hp.isHardCover());
true
System.out.println(hp.getDamages());
0
System.out.println(hp.repairBook());
false
hp.addDamages(49);
System.out.println(hp.getDamages());
49
System.out.println(hp.repairBook());
false
hp.addDamages(1);
System.out.println(hp.getDamages());
50
System.out.println(hp.repairBook());
true
Activity3.16.2.
Write the class Book below with the appropriate instance variables, constructor, and methods described in main method and in the table above.
Subsection3.16.3Present Class
Write a class called Present that describes a gift for an occasion. Use the method calls in the main method below to create the appropriate instance variables and methods for the Present class.
public static void main(String[] args)
{
//creates a Present object
Present gift = new Present("Birthday", 29.99, "Legos");
//prints out the gift name and cost
System.out.println("The gift is " + gift.getName()
+ ", and it costs $" + gift.getPrice() );
// prints out the reaction "Wow!"
System.out.println("The reaction when opening the gift was "
+ gift.reaction() );
// Prints out "Purchased at local store"
gift.purchasedAt("local store");
}
}
Activity3.16.3.
Write the class Present below with the appropriate instance variables, constructor, and methods described in main method.