Created
September 30, 2015 04:44
-
-
Save DavidGinzberg/7e0d3dac4a339f6b348e to your computer and use it in GitHub Desktop.
Some badly written code to help learn and practice polymorphism concepts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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