![]() |
![]() |
![]() |
![]() |
![]() |
|
Having arranged to access the meter
and movie instance variables via getters, you can move into the
getters the meter and movie construction operations, calling the meter or
movie constructors only when your program first needs meter or movie
values.
The principal benefit of on-demand construction is that you eliminate
the danger that your program will ask a variable for a value before that
value has been supplied. Liberal use of the idiom involved dramatically
reduces the occurrence of bugs that throw instances of a
NullPointerException exception.
import javax.swing.*;
import java.awt.event.*;
public class MovieApplication extends JFrame {
public static void main (String argv []) {
new MovieApplication("Movie Application");
}
// Declare instance variables:
private Meter meter;
private Movie movie;
// Define constructor
public MovieApplication(String title) {
super(title);
// Create model
getMovie();
// Create and connect view to application
getContentPane().add("Center", getMeter());
// Connect window listener, size and show
addWindowListener(new LocalWindowListener());
setSize(300, 100);
show();
}
// Define getters and setters
public Meter getMeter () {
if (meter == null) {
setMeter(new Meter(0, 30));
}
return meter;
}
public Movie getMovie () {
if(movie == null) {
setMovie(new Movie (10, 10, 10, "On to Java"));
}
return movie;
}
public void setMeter (Meter m) {meter = m;}
public void setMovie (Movie m) {movie = m;}
// Define window adapter
private class LocalWindowListener extends WindowAdapter {
public void windowClosing(WindowEvent e) {
System.exit(0); return;
}}}