What is Initializing Fields ?
Fields can (and often should) be initialized while 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 = 123.45; // 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 CarTest2.java
$ java CarTest
is moving at 0.0 kilometers per hour.