Transcript L5

Object Arrays
What is an object array
class object
{
int x;
int y;
int z;
}
void main()
{
object[ ] ob1 = new object[10]
}
How do we use them? First initialize
constructors before use.
class object
{
int x;
int y;
int z;
}
void main()
{
object[ ] ob1 = new object[10]
for(int k = 0; k < 10; k++)
{
ob1[k] = new object();
}
}
How do we use them? First initialize
constructors before use.
class object
{
int x;
int y;
int z;
}
void main()
{
ob1[0].x = 15;
ob1[1].x = 20;
ob1[3].z = 50;
}
Things to remember:
• The rules regarding arrays apply here including:
• Make sure array doesn’t go out of bounds
• Array size must be declared before run time
• The rules regarding how classes are governed including:
•
•
•
•
Private / public access
Static / final variables usage
Understand how constructors work
Understand the scope of variables and methods in a class
Exercise 1
Create a class called Numbers with the following three data types:
• private int num1;
• private int num2
• private int num3;
Create a constructor that will generate random values for all three
integers in this class.
In void main, declare an array of 5 Numbers. Run their constructors.
Exercise 2
Now create the toString() method for the class and let’s have some
output.
Exercise 3
Write a method that will take the three values generated and return
the average.
Now in void main, output the averages from least to greatest.
Exercise 4
Create a class called Parents with the following data:
• private String name;
• private boolean hasChild
• private int age;
Create a constructor that asks for parent’s name, age, and if they have
children.
Create a toString method that will output the results.
In void main, declare an array of Parents (5 is enough) and let’s get
output.
Exercise 5
Now create a class called People. In people declare an array of
Students (5 should be enough). Attempt to output all your data.