Programming Drill #19

Due: Monday, November 19
Goal:  More practice with inheritance

Here is an alcoholic beverage class. It has expanded on our previous definition of the Beer class to include wine. There is a 'type' variable set to 0 if it is beer and 1 if it is wine. This is used to calculate the number of drinks, because there are only 5 ounces in a glass of wine but 12 ounces in a glass of beer.

public class AlcoholicBeverage
{
	private String name;
	private double alcohol;
	private int type;		// 0 for Beer, 1 for Wine

	// Constructors
	public AlcoholicBeverage()
	{
		name = "";
		alcohol = 0.0;
	}

	public AlcoholicBeverage(String newName, double newAlcohol, int newType)
	{
		name = newName;
		alcohol = newAlcohol;
		type = newType;
	}

	// Accessors
	public String getName()
	{
		return name;
	}
	public double getAlcohol()
	{
		return alcohol;
	}
	// Mutators
	public void setName(String newName)
	{
		name = newName;
	}
	public void setAlcohol(double newAlcohol)
	{
		alcohol = newAlcohol;
	}

	// This method returns the number of drinks that a person
	// of (weight) pounds can drink using the alcohol percentage in this
	// drink.  Beer is 12 ounces while wine is 5 ounces.
	// It is an estimate.  It assumes the legal limit is 0.08 BAC.
	public double intoxicated(double weight)
	{
		double numDrinks;
		// This is a simplification of the Widmark formula
		if (type == 0)
		{
			// Beer
			numDrinks =  (0.08 + 0.015) * weight / (12 * 7.5 * alcohol);
		}
		else
		{
			// Wine
			numDrinks =  (0.08 + 0.015) * weight / (5 * 7.5 * alcohol);
		}
		return numDrinks;
	}


	/////////////////////////////////////////////////////////////////
	// Main Method
	/////////////////////////////////////////////////////////////////

	public static void main(String[] args)
	{
		AlcoholicBeverage drink1 = new AlcoholicBeverage("Guiness",0.074, 0);  // 0 for beer
		AlcoholicBeverage drink2 = new AlcoholicBeverage("Zinfandel", 0.20, 1); // 1 indicates wine

		double drinks;

		// How many drinks that Bubba can drink
		drinks = drink1.intoxicated(250);
		System.out.printf("Bubba at 250 pounds can drink about " + drinks + " " +
						   drink1.getName() + "'s in one hour until intoxicated.\n");

		drinks = drink2.intoxicated(250);
		System.out.printf("Bubba at 250 pounds can drink about " + drinks + " " +
						   drink2.getName() + "'s in one hour until intoxicated.\n");
	}
}
    

This program will run but it is not very convenient to add a new type of drink - we'd have to add a new code to the 'type' variable. And what if type gets set to an invalid number, like 3? A better organization is to use inheritance.

Show your completed program to your instructor or email it to kenrick@uaa.alaska.edu by the end of the day.