Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

arrays of classes

0 views
Skip to first unread message

The Wilkinsons

unread,
Nov 16, 1998, 3:00:00 AM11/16/98
to

silver...@my-dejanews.com wrote in message
<72qjks$iov$1...@nnrp1.dejanews.com>...
>Could somebody please tell if there is a way to define an array of classes.
>If there is, how might I go about doing so.
>
>What I'm looking to do is shown very roughly in the following code snipet.
>
>public class rectangle
>{
> public int getwidth()...
>}
>
>
>Once I have defined an array of classes such as this I wish to then be able
to
>make method calls such as:
>
>array_name[i].getwidth(); Where array_name[i] is one instance of
the
> class rectangle.
>
>Is there a way to define arrays of classes so that this sort of thing can
be
>done?
>


Sure!

...
rectangle[ ] array_name = new rectangle[ 100 ]; // or whatever size
for ( int n = 0; n < 100; ++n )
{
array_name[ n ] = new rectangle( );
}
...
int i = 99;
int wide = array_name[i].getwidth( );
...

Why do I get the feeling that you need to read one
more chapter ahead in your text book? (HUGE grin)

Note the difference between Java and other languages
here: creating the array, per se, creates only an array
of object REFERENCES, *not* the objects themselves.
You must then create the actual objects and assign
references to them to the elements of the array.

p.s.: The proper term is "array of objects". Technically,
an array of classes in Java would probably be expressed
as an array of java.lang.Class. But even that would be
misleading, as it would really be an array of Class objects.

Anyway, classes exist only at compilation time; at run time,
you work with INSTANCES of classes, and those are
objects.


silver...@my-dejanews.com

unread,
Nov 17, 1998, 3:00:00 AM11/17/98
to
Could somebody please tell if there is a way to define an array of classes.
If there is, how might I go about doing so.

What I'm looking to do is shown very roughly in the following code snipet.

public class rectangle
{
private int width;
private int height;

public rectangle(int initial_width, int initial_height)
{
width = initial_width;
height = initial_height;
}

public int getwidth()
{
return (width);
}

public int getheight()
{
return (height);
}
}


Once I have defined an array of classes such as this I wish to then be able to
make method calls such as:

array_name[i].getwidth(); Where array_name[i] is one instance of the
class rectangle.

Is there a way to define arrays of classes so that this sort of thing can be
done?


-----------== Posted via Deja News, The Discussion Network ==----------
http://www.dejanews.com/ Search, Read, Discuss, or Start Your Own

0 new messages