|
Re: What's the difference between robotInit() and constructor in SimpleRobot?
There are some reasons to prefer doing initialization in robotInit() instead of the constructor for FRC, but at the end of the day the difference is minor.
First, some background on how a Java program runs on the cRIO. We are using J2ME (not J2SE as on a desktop PC), and the main type of app we run is called a MIDlet. MIDlets are basically a common way to start, pause, and stop Java applications on mobile devices. If you look at the WPIlib code, RobotBase (which is the Parent of IterativeRobot and SimpleRobot) extends MIDlet.
MIDlets basically have three methods that define them: startApp(), pauseApp(), and destroyApp(). These three methods do exactly what they sound like: startApp() kicks off your program, pauseApp() causes it to enter a paused state (after which startApp() would be called again to resume), and destroyApp() kills it. In FRC we never use the pause/resume functionality.
So we already hit on one key difference between the constructor and startApp() - startApp() can be called more than once if the MIDlet is paused and resumed. As a result the developer should make sure you don't re-allocate resources that were not freed up during the call do pauseApp(). Again, in FRC it doesn't matter because we never pause.
A second difference is that the MIDlet always has access to the user's display during startApp(), but not necessarily during the call to the constructor. Remember, J2ME was designed for phones and similar devices - obviously we don't have a display.
robotInit() is called during startApp() by IterativeRobot/SimpleRobot. The built-in boilerplate code in RobotBase and IterativeRobot/SimpleRobot does a couple of things for you before it calls robotInit(). First, it sets a couple of diagnostics flags that let the driver station/FMS know that your robot is alive and booting up. Second, it wraps the call to robotInit() in a catch all block - if you throw an exception in robotInit(), the catch block will print out a stack trace for you. This is very helpful - definitely better than just watching your code die with no diagnostics.
|