Showing Page:
1/17
C208 Object-Oriented Programming
Week 13 Lesson 26
Worksheet
Page 1
OFFICIAL (CLOSED) \ NON-SENSITIVE
A. Loops, Arrays, Objects
Study the class diagram and table given below.
Class
Constructor/
Method
Description
Pear
Pear(String)
This constructor takes in the name of the Pear,
and assign this value to the name field of the Pear
object when instantiated.
Colour is set to “Green”.
Pear(String, String)
This constructor takes in the name and colour of
the Pear, and assigns these values to the field of
the Pear object when instantiated.
displayPear()
This method displays the name and colour of the
Pear.
Sample output (if name of Pear is ‘Anjou’ and
colour is ‘Green’):
Name: Anjou
Colour: Green
1. Create the Pear class based on the class diagram and description above.
public class Pear {
public String name;
public String colour;
public Pear(String name) {
this.name = name;
this.colour = "Green";
}
public Pear(String name, String colour) {
this.name = name;
this.colour = colour;
}
Showing Page:
2/17
Page 2
OFFICIAL (CLOSED) \ NON-SENSITIVE
public void displayPear() {
System.out.println("Name: " + name);
System.out.println("Colour: " + colour);
}
}
2. Create a class named PearMain.
In PearMain, declare and create an array to store 15 Pear objects. Name this array pearBasket .
Pear[] pearBasket = new Pear[14];
3. Create the following pears in PearMain :
Pear pear1 = new Pear(“Forelle”, “Red”);
Pear pear3 = new Pear(“Concorde”);
Pear pear5 = new Pear(“Comice”, “Red”);
In PearMain, write code to add the pears above into the first, third and fifth positions in the
pearBasket array respectively.
Pear pear1 = new Pear("Forelle", "Red");
Pear pear3 = new Pear("Concorde");
Pear pear5 = new Pear("Comice", "Red");
pearBasket[1] = pear1;
pearBasket[3] = pear3;
pearBasket[5] = pear5;
4. In PearMain, using a for/while loop, write code to display all the pears.
for(int i =0; i < pearBasket.length;i++) {
if(pearBasket[i] != null) {
pearBasket[i].displayPear();
}
}
Showing Page:
3/17
Page 3
OFFICIAL (CLOSED) \ NON-SENSITIVE
5. In PearMain, using a for/while loop, write code to count the number of Pear objects in the
pearBasket array.
for(int j =0; j < pearBasket.length;j++) {
if(pearBasket[j] != null) {
count++;
}
}System.out.println("There are " + count + " pears");