![]() |
![]() |
![]() |
![]() |
![]() |
|
Now, suppose that you have defined the Attraction class, the Movie
class, and the Symphony class as in Segment 316. If you then
declare an array for instances of the Attraction class, you can
place Movie instances and Symphony instances in that array,
because the value of an element of an array declared for a particular class
can be an instance of any subclass of that class.
For example, you can compute the average rating of a mixed array of
Movie and Symphony instances:
public class Demonstrate {
public static void main (String argv[]) {
int sum = 0;
Attraction attractions[] = {new Movie(4, 7, 3),
new Movie(8, 8, 7),
new Symphony(10, 9, 3),
new Symphony(9, 5, 8)};
for (int counter = 0; counter < attractions.length; ++counter) {
sum = sum + attractions[counter].rating();
}
System.out.print("The average rating of the " + attractions.length);
System.out.println(" attractions is " + sum / attractions.length);
}
}
--- Result ---
The average rating of the 4 attractions is 20