Skip to content

Instantly share code, notes, and snippets.

@DavidGinzberg
Created September 30, 2015 04:44
Show Gist options
  • Save DavidGinzberg/7e0d3dac4a339f6b348e to your computer and use it in GitHub Desktop.
Save DavidGinzberg/7e0d3dac4a339f6b348e to your computer and use it in GitHub Desktop.
Some badly written code to help learn and practice polymorphism concepts
// File: Car.java
// Author: David Ginzberg
// Purpose: A small metaphorical program for practicing polymorphic
// code design and using interfaces
package polymorphism;
public class Car{
private enum Model{
CIVIC, CHARGER, Z4, JETTA;
}
protected enum Fuel{
REGULAR, MIDGRADE, PREMIUM, DIESEL, AVGAS;
}
Model model;
Fuel fuel;
public Car(){
model = Model.CIVIC;
fuel = Fuel.REGULAR;
}
public Car(int whichOne){
switch(whichOne){
default:
case 1:
model = Model.CIVIC;
fuel = Fuel.REGULAR;
break;
case 2:
model = Model.CHARGER;
fuel = Fuel.MIDGRADE;
break;
case 3:
model = Model.Z4;
fuel = Fuel.PREMIUM;
break;
case 4:
model = Model.JETTA;
fuel = Fuel.DIESEL;
break;
}
}
public void drive(){
System.out.println("Driving my " + this);
}
public void refuel(){
System.out.println("Refuelling my " + this + " with " + fuel.name());
}
public void testEmissions(){
System.out.println("Emissions test for " + this + ". It passed.");
if(model == Model.JETTA && fuel == Fuel.DIESEL){
System.out.println("...But something's fishy...");
}
}
public String toString(){
return model.name();
}
}
// File: Car.java
// Author: David Ginzberg
// Purpose: Driver class for Car.java example
package polymorphism;
import polymorphism.Car;
public class TestDrive{
public static void main(String[] args){
Car[] myCars = {
new Car(1),
new Car(2),
new Car(3),
new Car(4)
};
for(Car myCar : myCars){
myCar.drive();
myCar.refuel();
myCar.testEmissions();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment