Class 1, Part 2 | Intro to Java 30-IT-396 |
More About Inheritance
// Attributes specific to class Vehicle and its
subclasses
protected int gallonsOfGas;
protected int location;
protected int mpg;
protected int miles;
protected int numberOfTires;
// Constructor to initialize attributes.
public Vehicle(int gallonsOfGas, int mpg)
{
this.gallonsOfGas =
gallonsOfGas;
this.mpg = mpg;
}
// Go method for Vehicle and its subclasses
public void go(int distance) {
location += distance;
gallonsOfGas = gallonsOfGas
- (distance * mpg);
}
}
// A subclass of Vehicle
publiuc class Car extends Vehicle {
// Attributes specific to class Car and its subclasses.
protected int numberOfDoors;
protected int numberOfGears;
// Constructor for Car.
// Initializes variables and calls constructor
for Vehicle.
public Car(int gallonsOfGas, int numberOfDoors,
int numberOfGears, int mpg)
{
super(gallonsOfGas,
mpg);
this.numberOfDoors =
numberOfDoors;
this.numberOfGears =
numberOfGears;
numberOfTires = 4;
}
}
// This class extends Car.
public class Cavalier extends Car {
static int cavMpg = 30;
public Cavalier(int gallonsOfGas, int numberOfDoors,
int numberOfGears)
{
super (gallonsOfGas,
numberOfDoors, numberOfGears, mpg);
}
}
// Class Hybrid extends Car
public class Hybrid extends Car {
// Attributes specific to Hybrid
protected int kwhRemaining;
protected int mpkwh;
protected boolean electricMode;
protected int minkwh;
// Constructor for Hybrid.
// Initializes attributes and calls cosntructor
for Car.
public Hybrid(int kwhRemaining, int gallonsOfGas,
int numberOfDoors, int numberOfGears, int mpg) {
super(gallonsOfGas,
numberOfDoors, numberOfGears, mpg);
this.kwhRemaining =
kwhRemaining;
}
// go() method overrides go() method of Vehicle
superclass.
public void go(int distance) {
if (electricMode) {
location += distance;
kwhRemaining = kwhRemaining - (distance * mpkw);
if (kwhRemaining < minkwh) {
electricMode = false;
}
} else {
super.go(distance);
}
}
// Method specific to class Hybrid
public void setElectricMode(boolean electricMode)
{
this.electricMode =
electricMode;
}
// Method specific to class Hybrid
public boolean isElectricMode() {
return electricMode;
}
}
Created by: Brandan
Jones January 4, 2002