QUESTION #3 – LOTSA
CLOWNS (SELF-CHECK)
SOLUTIONS
Copy the
code from this Clown class to your project. Examine the Clown class to get an
understanding of it. Below are a few
questions to help you examine the Clown class.
PART A – OOP REVIEW
A)
How many instance variables does the class have?
It has three instance variables: height,
behavior and shoes.
B)
Are the instance variables accessible from other
classes?
No they are not because they are all private.
C)
Once a Clown instance is created, is it possible
to change any of the instance variables?
It is not possible change the height and shoes instance variables. However, one can change the behaviour
instance variable by using the makeAngry() method.
D)
What line of code is required to create an
instance of Clown named bozo?
Clown
bozo = new Clown();
E)
What line of code is needed to output a String
representation of the Clown object to screen? Try it.
System.out.println(bozo);
PART B – ARRAYS
F)
Write the statement(s) that create(s) a Clown
array that contains 8 clowns. Make
sure the Clown objects are created as well.
Option #1:
Clown[] circus = new
Clown[8];
circus[0]
= new Clown();
circus[1]
= new Clown();
circus[2]
= new Clown();
circus[3]
= new Clown();
circus[4]
= new Clown();
circus[5]
= new Clown();
circus[6]
= new Clown();
circus[7]
= new Clown();
Option #2:
Clown[] circus = new
Clown[8];
for(int i=0; i<circus.length; i++)
{
circus[i] = new
Clown();
}
Option #3: (Should all be on one
line of code)
Clown[] circus = {new
Clown(), new Clown(), new
Clown(), new Clown(), new
Clown(), new Clown(), new
Clown(), new Clown()};
G)
Use a for loop to output the String
representation of each Clown instance in the array one at a time.
for (int i=0; i<circus.length; i++)
{
System.out.println(circus[i]);
}
The above code will
output something like this:
A tall silly clown with big blue shoes.
A short cranky clown with big blue shoes.
A short silly clown with sparkly purple shoes.
A short silly clown with floppy red shoes.
A short giggly clown with big blue shoes.
A tall happy clown with sparkly purple shoes.
A tall cranky clown with sparkly purple shoes.
A tall silly clown with floppy
red shoes.
H)
Use another for loop to make all Clown instances
angry. Then, in yet another for
loop, output String representations of each Clown once again to make sure
they truly are angry clowns.
for (int i=0; i<circus.length; i++)
{
circus[i].makeAngry();
}
for (int i=0; i<circus.length; i++)
{
System.out.println(circus[i]);
}
|