Contents
- ./Car.java
- ./CarLot.java
- ./Chicken.java
- ./CustomerServiceOrder.java
- ./Electric.java
- ./Hybrid.java
- ./Movable.java
- ./Powered.java
- ./TestAbstractClass.java
- ./TestInterface.java
./Car.java 1/10
[top][prev][next]
/**
* Demonstrates use of interface.
* Since Car implements Powered, which extends Movable, Car must implement
* the move method and the milesPerGallon method.
*/
public class Car implements Powered {
private double mpg;
private double xcoord;
private double ycoord;
protected int tankSize = 15; // in gallons
public Car(double mpg) {
this.mpg = mpg;
xcoord = 0;
ycoord = 0;
}
@Override
public String toString() {
return xcoord + ", " + ycoord;
}
public double milesPerGallon() {
return mpg;
}
public void move(double x, double y) {
xcoord += x;
ycoord += y;
}
public int getTankSize() {
System.out.println("Car's getTankSize()");
return tankSize;
}
public static String staticMethod() {
return "Car's static method";
}
public static void main(String args[]) {
Car car = new Car(32);
car.move(1, 1);
System.out.println(car);
System.out.println(SPEED_LIMIT);
System.out.println(car.getTankSize());
System.out.println(staticMethod());
}
}
./CarLot.java 2/10
[top][prev][next]
/**
* Demonstrates polymorphism
* and that static methods are inherited but cannot be overridden.
*/
public class CarLot {
public static void main(String[] args) {
Car[] mycars = new Car[3];
Car car = new Car(35);
Hybrid hybrid = new Hybrid();
Electric electric = new Electric();
mycars[0] = car;
mycars[1] = hybrid;
mycars[2] = electric;
// note that mycar[1] and hybrid are two variables referencing
// the *same* object--of type Hybrid.
// This code calls an instance method, so dynamic dispatch is used.
// Both execute the Hybrid class's method
System.out.println(hybrid.getTankSize());
System.out.println(mycars[1].getTankSize());
// This code calls a static method.
// The first will call Hybrid's static method, which makes sense
// The second will call Car's static method, because mycars[1] is a
// Car variable. Dynamic dispatch is not used.
System.out.println(hybrid.staticMethod());
System.out.println(mycars[1].staticMethod());
// Output:
// Hybrid's static method
// Car's static method
}
}
./Chicken.java 3/10
[top][prev][next]
import java.util.Arrays;
/**
* A Java class that models a Chicken. The state of the chicken is its
* name, height, weight, and sex.
*
* Made several of the accessor methods final because child classes
* shouldn't need to change them.
*
* Implements the Comparable interface--using generics, comparing
* chickens by their height.
*
* @author CSCI209
*/
public class Chicken implements Comparable<Chicken> {
// ------------ INSTANCE VARIABLES -------------------
/** the chicken's name */
private String name;
/** the height of the chicken in centimeters */
private int height;
/** the weight of the chicken in pounds */
private double weight;
/** true iff the chicken is a female */
private boolean isFemale;
/** the name of the farm the chickens are on */
private static String FARM = "McDonald";
/** default name for chickens */
public static final String DEFAULT_NAME = "BUBBA";
/** the amount of weight the chicken gains during feeding */
private static final double WEIGHT_GAIN = .3;
/** the amount of height the chicken gains during feeding */
private static final int HEIGHT_GAIN = 1;
/** the amount of weight difference we are okay with */
public static final double ERROR_TOLERANCE = .0001;
/**
* Constructs a chicken with the given characteristics.
*
* @param name the name of the chicken
* @param height the height of the chicken in centimeters
* @param weight the weight of the chicken in pounds
* @param isFemale whether the chicken is female
*/
public Chicken(String name, int height, double weight, boolean isFemale ) {
this.name = name;
this.height = height;
this.weight = weight;
this.isFemale = isFemale;
}
/**
* Constructs a chicken with the given characteristics and assumes
* the chicken is female.
*
* @param name the name of the chicken
* @param height the height of the chicken in centimeters
* @param weight the weight of the chicken in pounds
*/
public Chicken(String name, int height, double weight) {
this( name, height, weight, true );
}
/**
* Constructs a chicken with the given characteristics, assumes
* the chicken's name is Bubba (defined by DEFAULT_NAME) and that
* it is female.
* @param height the height of the chicken in centimeters
* @param weight the weight of the chicken in pounds
*/
public Chicken( int height, double weight ) {
this( DEFAULT_NAME, height, weight, true);
}
/**
* Returns a string representation of the chicken.
* Format:
* <br/>Chicken name: <name>
* <br/>weight: <weight> pounds
* <br/>height: <height> cm
* <br/>female/male
* <p>Weight is displayed to one decimal place
* @return a string representation of this Chicken
*/
@Override
public String toString() {
StringBuffer rep = new StringBuffer("Chicken name: ");
rep.append(name);
rep.append("\nweight: ");
rep.append(String.format("%.1f", weight));
rep.append(" pounds\nheight: ");
rep.append(height);
rep.append(" cm\n");
rep.append( isFemale? "female" : "male"); // Java ternary operator; also available in C
return rep.toString();
}
/**
* Determines if two Chickens are equivalent, based on their
* name, height, weight, and sex.
*/
@Override
public boolean equals(Object o) {
if( o == this ) {
return true;
}
Chicken other = (Chicken) o;
if( ! other.getName().equals(this.getName() ) ) {
return false;
}
if( other.getHeight() != this.getHeight() ) {
return false;
}
double difference = this.getWeight() - other.getWeight();
if( difference > ERROR_TOLERANCE || difference < -ERROR_TOLERANCE) {
return false;
}
return this.isFemale() == other.isFemale();
}
/**
* Returns a negative integer if this chicken is smaller
* in height than than the object passed as a parameter,
* returns a positive integer if this chicken is greater in height
* than the object passed as a parameter, and returns a 0 if the
* two chickens have the same height.
* (Could make different decisions about how to compare chickens.)
*/
@Override
public int compareTo(Chicken other) {
if (height < other.getHeight() )
return -1;
if (height > other.getHeight())
return 1;
return 0;
// simpler implementation : return height-other.getHeight()
}
//
// ----------- GETTER METHODS ------------
// (also Accessor methods)
/**
* Returns the height of the chicken in centimeters
*
* @return the height of the chicken, in centimeters
*/
public final int getHeight() {
return height;
}
/**
* Returns the weight of the chicken in pounds
* @return the weight of the chicken, in pounds
*/
public final double getWeight() {
return weight;
}
/**
* Returns the chicken's name
* @return the name of the chicken
*/
public final String getName() {
return name;
}
/**
* Returns whether this chicken is female.
*
* @return true if the chicken is female and false otherwise.
*/
public boolean isFemale() {
return isFemale;
}
//
// ------------- MUTATORS -----------
//
/**
* Feeds the chicken--making the chicken grow
*/
public void feed() {
weight += WEIGHT_GAIN;
height += HEIGHT_GAIN;
}
//
// ------------- SETTERS ----------
//
/**
* Sets the name of the chicken
*
* @param n
* the name of the chicken
*/
public void setName(String n) {
name = n;
}
/**
* Sets the height of the chicken
*
* @param h
* the height of the chicken, in cm
*/
public void setHeight(int h) {
height = h;
}
/**
* Sets the weight of the chicken
*
* @param weight
* the weight of the chicken, in pounds
*/
public void setWeight(double weight) {
this.weight = weight;
}
/**
* @param args
* the command-line arguments
*/
public static void main(String args[]) {
// Tests focus on Comparable interface implementation.
// Better to have all tests in one method. See previous
// implementations for those tests.
int fredHeight = 38;
Chicken chicken = new Chicken("Fred", fredHeight, 2.0, false);
String[] names = {"Rocky", "Baby Chicken"};
double[] weights = {4.0, .8};
int[] heights = {50, 4};
Chicken[] chickens = new Chicken[3];
for( int i=0; i < names.length; i++ ) {
Chicken thisChicken = new Chicken( names[i], heights[i], weights[i] );
chickens[i] = thisChicken;
}
chickens[2] = chicken;
if( chicken.compareTo(chicken) != 0 ) {
System.err.println("Comparing a chicken to itself should be 0.");
}
System.out.println("Comparing " + chicken + " to " + chickens[0]);
System.out.println();
System.out.println(chicken.getName() + " compareTo " + chickens[0].getName() );
System.out.println(chicken.compareTo(chickens[0]));
if( chicken.compareTo(chickens[0]) >= 0 ) {
System.err.println("Suspected error in compareTo implementation.");
}
System.out.println(chickens[0].getName() + " compareTo " + chicken.getName() );
System.out.println(chickens[0].compareTo(chicken));
if( chickens[0].compareTo(chicken) <= 0 ) {
System.err.println("Suspected error in compareTo implementation.");
}
System.out.println("\nSort the chickens by height:");
// sort the chickens
Arrays.sort(chickens);
// print the chickens in sorted order (by height)
for (Chicken c : chickens) {
System.out.println(c);
}
}
}
./CustomerServiceOrder.java 4/10
[top][prev][next]
public static void abstractedVersion(String[] args) {
CustomerServiceOrder customerOrder = new FIFOOrder();
while( agent.isAvailable() ) {
if( customerOrder.hasNext() ) {
Customer next = customerOrder.getNextCustomer();
agent.handle( next );
}
}
}
public static void originalVersion(String[] args) {
while(agent.isAvailable()) {
if( customerList.size() > 0 ) {
Customer next = list.remove(0);
agent.handle( next );
}
}
}
./Electric.java 5/10
[top][prev][next]
/**
* Demonstrates extension of a class that implements an interface.
* Shows what happens if have a staticMethod -- inherited but not overridden.
* Prints Car's static method
*/
public class Electric extends Car {
/**
* Creates an Electic car with a MPG of 200
*/
public Electric() {
super(200);
tankSize = 0;
}
public int getTankSize() {
System.out.println("Electric's getTankSize()");
return tankSize;
}
public static void main(String args[]) {
Electric car = new Electric();
car.move(1, 1);
System.out.println(car);
System.out.println(SPEED_LIMIT);
System.out.println(car.getTankSize());
System.out.println(staticMethod()); // calls Car's static method
}
}
./Hybrid.java 6/10
[top][prev][next]
/**
* Demonstrates extension of a class that implements an interface.
* Shows what happens if have a staticMethod -- inherited but not overridden.
*/
public class Hybrid extends Car {
/**
* Creates a Hybrid car with a MPG of 45
*/
public Hybrid() {
super(45);
tankSize = 10;
}
public static String staticMethod() {
return "Hybrid's static method";
}
public int getTankSize() {
System.out.println("Hybrid's getTankSize()");
return tankSize;
}
public static void main(String args[]) {
Hybrid car = new Hybrid();
car.move(1, 1);
System.out.println(car);
System.out.println(SPEED_LIMIT);
System.out.println(car.getTankSize());
System.out.println(staticMethod());
}
}
./Movable.java 7/10
[top][prev][next]
public interface Movable {
void move(double x, double y);
}
./Powered.java 8/10
[top][prev][next]
public interface Powered extends Movable {
double milesPerGallon();
double SPEED_LIMIT = 95;
}
./TestAbstractClass.java 9/10
[top][prev][next]
/**
* A toy class to demonstrate that an abstract class can implement
* an interface and not implement all of the interface's methods.
*/
public abstract class TestAbstractClass implements TestInterface {
// doesn't implement aMethod from TestInterface
}
./TestInterface.java 10/10
[top][prev][next]
/**
* A toy interface to demonstrate that an abstract class can implement
* an interface and not implement all of the interface's methods.
*/
public interface TestInterface {
void aMethod();
}
Generated by GNU Enscript 1.6.5.90.