Can a programmer write a definition for the class Car
?
Of course! When you need a class that does something, and it has not already been defined, you can write the definition youself.
Here is the miles per gallon program.
Both the class Car
and
the testing class MilesPerGallon
are in the same source file,
so you don't need to say import Car
like the previous page did.
To keep the program short, user interaction has been left out.
import java.io.* ; class Car { // instance variables // constructor // methods } class MilesPerGallon { public static void main( String[] args ) { Car car = new Car( 32456, 32810, 10.6 ); System.out.println( "Miles per gallon is " + car.calculateMPG() ); } }
The source file must be named MilesPerGallon.java
after the name of
the class that contains main()
.
Decide what variables should go in the data section. Look back to the Car class for the class to see what you need.