Initializing Fields

Fields can (and often should) be initialized when they're declared, just like local variables.

class Car {

  String licensePlate = "";    // e.g. "New York 543 A23"
  double speed        = 0.0;   // in kilometers per hour
  double maxSpeed;    = 120.0; // in kilometers per hour

}
The next program creates a new car and prints it:

class CarTest2 {

  public static void main(String args[]) {
    
    Car c = new Car();
    
    System.out.println(c.licensePlate + " is moving at " + c.speed + 
      "kilometers per hour.");    
  }
  
}
For example,

% javac Car.java
% javac CarTest.java
% java CarTest
 is moving at 0.0 kilometers per hour.


Previous | Next | Top
Last Modified October 1, 1999
Copyright 1999 Elliotte Rusty Harold
elharo@metalab.unc.edu