Prev | Current Page 211 | Next

Carl Reynolds and Paul Tymann

"Schaum's Outline of Principles of Computer Science"

The first two parameters are String values, and the last two are ints.
When another program asks for an instance of an Automobile, the constructor will create an
Automobile object and return to the other program a reference to the new Automobile. A reference is an
address. The other program can then use the reference to the new Automobile object to manipulate it.
/**Class Automobile
* Illustrating instance and static varibles
* and methods
* @author Carl Reynolds
*/
class Automobile {
//static variable
private static int count; //count of automobiles
//instance variables
private String make;
private String model;
private int year;
private int hp;
private double speed;
//Constructor
Automobile( String mk, String mdl, int yr, int power ) {
make = mk; //assign constructor parameters
model = mdl; // to private instance variables
year = yr;
hp = power;
count++; //add to count of Automobiles created
}
80 PROGRAMMING IN JAVA [CHAP. 5
//static method
static int getCount() {
return count;
}
//instance methods to set and get speed
public void accelerate( double newSpeed ) {
if( newSpeed > 70. ) speed = 70.;
else speed = newSpeed;
}
public double getSpeed() { return speed; };
//returns a text representation of an Automobile
public String toString() {
return year + " " + make + " " + model;
}
}
Here is a class which uses the Automobile class:
/**
* Class AutomobileFactory
* @author Carl Reynolds
*/
class AutomobileFactory {
public static void main( String[] args ) {
Automobile economy, family, sports;
economy = new Automobile(
"Kia", "Rio", 2006, 110 );
family = new Automobile(
"VW", "Passat", 2002, 170 );
sports = new Automobile(
"Ford", "Mustang", 2005, 300 );
System.


Pages:
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
kolej transsyberyjska Władysławowo wakacje alveo nasze hotele aurora amefa