Constructing objects with new

class Car {

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


To instantiate an object in Java, use the keyword new followed by a call to the class's constructor. Here's how you'd create a new Car variable called c:

  Car c;
  c = new Car();

The first word, Car, declares the type of the variable c. Classes are types and variables of a class type need to be declared just like variables that are ints or doubles.

The equals sign is the assignment operator and new is the construction operator.

Finally notice the Car() method. The parentheses tell you this is a method and not a data type like the Car on the left hand side of the assignment. This is a constructor, a method that creates a new instance of a class. You'll learn more about constructors shortly. However if you do nothing, then the compiler inserts a default constructor that takes no arguments.

This is often condensed into one line like this:

  Car c = new Car();

Previous | Next | Top | Cafe au Lait

Copyright 1997-1999 Elliotte Rusty Harold
Last Modified October 1, 1999