Java Reference
In-Depth Information
When an array of objects is built, all its elements
Date[i]
are initialized to
the
null
object.
1
Let us create a new kind of object for storing “events” that
are annotated dates, by defining the class
XEvent
as follows:
public class XEvent
{
Date when;
String what;
// Constructor
public XEvent(Date d, String text)
{
this.when=d;
this.what=text;
}
}
We can now write a static class function
static XEvent oldest(XEvent[]
tab)
attached to the class
TestXEvent
for seeking in an array and reporting
the oldest event as follows:
Program 5.7
The class
XEvent
and arrays of objects
class
TestXEvent
{
static void
Display (XEvent e )
{
System . out . print ( e . what+
": "
);
e.when.Display();
}
static boolean
older (XEvent e1 , XEvent e2 )
{
return
Date . isBefore (e1 .when , e2 .when) ;
}
static
XEvent o l d e s t (XEvent [ ]
tab )
{
XEvent r e s u l t=tab [ 0 ] ;
for
(
int
i=1;i
<
tab . length;++i )
if
(older(tab [ i ] , result )) result=tab [ i ];
return
result ;
}
public static void
main( String
[ ]
args )
{
Date d1=
new
Date(26 ,6 ,2003) ;
XEvent e1=
new
XEvent(d1 ,
"Birthday Julien"
);
Date d2=
new
Date(20 ,11 ,2000) ;
XEvent e2=
new
XEvent(d2 ,
"Birthday Audrey"
);
Date d3=
new
Date(23 ,6 ,1971) ;
XEvent e3=
new
XEvent(d3 ,
"Birthday Me"
);
Display(e1) ;
XEvent [ ] tabEvent=
new
XEvent [ 3 ] ;
tabEvent [0]= e1 ;
1
This can be interpreted as the equivalent of the zero initialization of primitive
types.
Search WWH ::
Custom Search