Car
object in a different classclass Car {
String licensePlate; // e.g. "New York 543 A23"
double speed; // in kilometers per hour
double maxSpeed; // in kilometers per hour
}
The next program creates a new car, sets its fields, and prints the result:
class CarTest {
public static void main(String args[]) {
Car c = new Car();
c.licensePlate = "New York A45 636";
c.speed = 70.0;
c.maxSpeed = 123.45;
System.out.println(c.licensePlate + " is moving at " + c.speed +
"kilometers per hour.");
}
}
This program requires not just the CarTest
class but also the Car
class. To make them work together put the Car
class
in a file called Car.java. Put the CarTest
class in a file called CarTest.java.
Put both these files in the same directory. Then compile both files in the usual way.
Finally run CarTest
. For example,
% javac Car.java % javac CarTest.java % java CarTest New York A45 636 is moving at 70.0 kilometers per hour.Note that
Car
does not have a main()
method
so you cannot run it. It can exist only when called by other programs
that do have main()
methods.Many of the applications you write from now on will use multiple classes. It is customary in Java to put every class in its own file. Next week, you'll learn how to use packages to organize your commonly used classes in different directories. For now keep all your .java source code and .class byte code files in one directory.