Modern Java Types
Enum with Fields and Methods
Your Planet enum needs mass and radius for each planet. Enums can have fields, constructors, and methods - they're full classes. Each constant can carry data and provide behavior.
Enum with fields
Add data to each enum constant.
// Enum with fields and constructor
// Concept: enum fields - storing data in enum constants
enum CoffeeSize {
SMALL(8, 2.50),
MEDIUM(12, 3.00),
LARGE(16, 3.50),
EXTRA_LARGE(20, 4.00);
private final int ounces;
private final double price;
// Enum constructor (always private)
CoffeeSize(int ounces, double price) {
this.ounces = ounces;
this.price = price;
}
// Getter methods
public int getOunces() {
return ounces;
}
public double getPrice() {
return price;
}
}
public class EnumWithFields {
public static void main(String[] args) {
// Access enum constant data
CoffeeSize mySize = ;
System.out.println("Size: " + mySize);
System.out.println("Ounces: " + mySize.getOunces());
System.out.println("Price: $" + mySize.getPrice());
// Print all sizes with details
System.out.println("\nAll coffee sizes:");
for (CoffeeSize size : CoffeeSize.values()) {
System.out.printf("%s: %doz - $%.2f%n",
size, size.getOunces(), size.getPrice());
}
// Calculate total for multiple coffees
CoffeeSize[] order = {
CoffeeSize.SMALL,
CoffeeSize.MEDIUM,
CoffeeSize.LARGE
};
double total = 0;
System.out.println("\nOrder:");
for (CoffeeSize size : order) {
System.out.printf(" %s: $%.2f%n", size, size.getPrice());
total += size.getPrice();
}
System.out.printf("Total: $%.2f%n", total);
}
}
// Enum with fields and constructor
// Concept: enum fields - storing data in enum constants
enum CoffeeSize {
SMALL(8, 2.50),
MEDIUM(12, 3.00),
LARGE(16, 3.50),
EXTRA_LARGE(20, 4.00);
private final int ounces;
private final double price;
// Enum constructor (always private)
CoffeeSize(int ounces, double price) {
this.ounces = ounces;
this.price = price;
}
// Getter methods
public int getOunces() {
return ounces;
}
public double getPrice() {
return price;
}
}
public class EnumWithFields {
public static void main(String[] args) {
// Access enum constant data
CoffeeSize mySize = ;
System.out.println("Size: " + mySize);
System.out.println("Ounces: " + mySize.getOunces());
System.out.println("Price: $" + mySize.getPrice());
// Print all sizes with details
System.out.println("\nAll coffee sizes:");
for (CoffeeSize size : CoffeeSize.values()) {
System.out.printf("%s: %doz - $%.2f%n",
size, size.getOunces(), size.getPrice());
}
// Calculate total for multiple coffees
CoffeeSize[] order = {
CoffeeSize.SMALL,
CoffeeSize.MEDIUM,
CoffeeSize.LARGE
};
double total = 0;
System.out.println("\nOrder:");
for (CoffeeSize size : order) {
System.out.printf(" %s: $%.2f%n", size, size.getPrice());
total += size.getPrice();
}
System.out.printf("Total: $%.2f%n", total);
}
}
// Enum with fields and constructor
// Concept: enum fields - storing data in enum constants
enum CoffeeSize {
SMALL(8, 2.50),
MEDIUM(12, 3.00),
LARGE(16, 3.50),
EXTRA_LARGE(20, 4.00);
private final int ounces;
private final double price;
// Enum constructor (always private)
CoffeeSize(int ounces, double price) {
this.ounces = ounces;
this.price = price;
}
// Getter methods
public int getOunces() {
return ounces;
}
public double getPrice() {
return price;
}
}
public class EnumWithFields {
public static void main(String[] args) {
// Access enum constant data
CoffeeSize mySize = ;
System.out.println("Size: " + mySize);
System.out.println("Ounces: " + mySize.getOunces());
System.out.println("Price: $" + mySize.getPrice());
// Print all sizes with details
System.out.println("\nAll coffee sizes:");
for (CoffeeSize size : CoffeeSize.values()) {
System.out.printf("%s: %doz - $%.2f%n",
size, size.getOunces(), size.getPrice());
}
// Calculate total for multiple coffees
CoffeeSize[] order = {
CoffeeSize.SMALL,
CoffeeSize.MEDIUM,
CoffeeSize.LARGE
};
double total = 0;
System.out.println("\nOrder:");
for (CoffeeSize size : order) {
System.out.printf(" %s: $%.2f%n", size, size.getPrice());
total += size.getPrice();
}
System.out.printf("Total: $%.2f%n", total);
}
}
Constructor assigns values. Each constant has its own data.
Enum methods
Add behavior to enums.
// Enum with methods
// Concept: enum methods - behavior in enum constants
enum Temperature {
FREEZING(32),
COLD(50),
MILD(65),
WARM(75),
HOT(90);
private final int fahrenheit;
Temperature(int fahrenheit) {
this.fahrenheit = fahrenheit;
}
// Convert to Celsius
public double toCelsius() {
return (fahrenheit - 32) * 5.0 / 9.0;
}
// Get description
public String getDescription() {
return switch (this) {
case FREEZING -> "Water freezes";
case COLD -> "Wear a jacket";
case MILD -> "Pleasant weather";
case WARM -> "T-shirt weather";
case HOT -> "Stay hydrated";
};
}
// Check if comfortable
public boolean isComfortable() {
return fahrenheit >= 65 && fahrenheit <= 75;
}
public int getFahrenheit() {
return fahrenheit;
}
}
public class EnumMethods {
public static void main(String[] args) {
// Use enum methods
Temperature current = ;
System.out.println("Temperature: " + current);
System.out.println("Fahrenheit: " + current.getFahrenheit());
System.out.println("Celsius: " + current.toCelsius());
System.out.println("Description: " + current.getDescription());
System.out.println("Comfortable? " + current.isComfortable());
// Print all temperatures with conversions
System.out.println("\nAll temperatures:");
for (Temperature t : Temperature.values()) {
System.out.printf("%s: %d°F = %.1f°C - %s%n",
t,
t.getFahrenheit(),
t.toCelsius(),
t.isComfortable() ? "✓" : "✗");
}
// Find comfortable temperatures
System.out.println("\nComfortable temperatures:");
for (Temperature t : Temperature.values()) {
if (t.isComfortable()) {
System.out.println(" " + t + ": " + t.getDescription());
}
}
// Compare temperatures
Temperature t1 = Temperature.COLD;
Temperature t2 = Temperature.HOT;
System.out.println("\nComparison:");
System.out.printf("%s (%d°F) vs %s (%d°F)%n",
t1, t1.getFahrenheit(),
t2, t2.getFahrenheit());
if (t1.getFahrenheit() < t2.getFahrenheit()) {
System.out.println(t1 + " is cooler");
}
}
}
// Enum with methods
// Concept: enum methods - behavior in enum constants
enum Temperature {
FREEZING(32),
COLD(50),
MILD(65),
WARM(75),
HOT(90);
private final int fahrenheit;
Temperature(int fahrenheit) {
this.fahrenheit = fahrenheit;
}
// Convert to Celsius
public double toCelsius() {
return (fahrenheit - 32) * 5.0 / 9.0;
}
// Get description
public String getDescription() {
return switch (this) {
case FREEZING -> "Water freezes";
case COLD -> "Wear a jacket";
case MILD -> "Pleasant weather";
case WARM -> "T-shirt weather";
case HOT -> "Stay hydrated";
};
}
// Check if comfortable
public boolean isComfortable() {
return fahrenheit >= 65 && fahrenheit <= 75;
}
public int getFahrenheit() {
return fahrenheit;
}
}
public class EnumMethods {
public static void main(String[] args) {
// Use enum methods
Temperature current = ;
System.out.println("Temperature: " + current);
System.out.println("Fahrenheit: " + current.getFahrenheit());
System.out.println("Celsius: " + current.toCelsius());
System.out.println("Description: " + current.getDescription());
System.out.println("Comfortable? " + current.isComfortable());
// Print all temperatures with conversions
System.out.println("\nAll temperatures:");
for (Temperature t : Temperature.values()) {
System.out.printf("%s: %d°F = %.1f°C - %s%n",
t,
t.getFahrenheit(),
t.toCelsius(),
t.isComfortable() ? "✓" : "✗");
}
// Find comfortable temperatures
System.out.println("\nComfortable temperatures:");
for (Temperature t : Temperature.values()) {
if (t.isComfortable()) {
System.out.println(" " + t + ": " + t.getDescription());
}
}
// Compare temperatures
Temperature t1 = Temperature.COLD;
Temperature t2 = Temperature.HOT;
System.out.println("\nComparison:");
System.out.printf("%s (%d°F) vs %s (%d°F)%n",
t1, t1.getFahrenheit(),
t2, t2.getFahrenheit());
if (t1.getFahrenheit() < t2.getFahrenheit()) {
System.out.println(t1 + " is cooler");
}
}
}
// Enum with methods
// Concept: enum methods - behavior in enum constants
enum Temperature {
FREEZING(32),
COLD(50),
MILD(65),
WARM(75),
HOT(90);
private final int fahrenheit;
Temperature(int fahrenheit) {
this.fahrenheit = fahrenheit;
}
// Convert to Celsius
public double toCelsius() {
return (fahrenheit - 32) * 5.0 / 9.0;
}
// Get description
public String getDescription() {
return switch (this) {
case FREEZING -> "Water freezes";
case COLD -> "Wear a jacket";
case MILD -> "Pleasant weather";
case WARM -> "T-shirt weather";
case HOT -> "Stay hydrated";
};
}
// Check if comfortable
public boolean isComfortable() {
return fahrenheit >= 65 && fahrenheit <= 75;
}
public int getFahrenheit() {
return fahrenheit;
}
}
public class EnumMethods {
public static void main(String[] args) {
// Use enum methods
Temperature current = ;
System.out.println("Temperature: " + current);
System.out.println("Fahrenheit: " + current.getFahrenheit());
System.out.println("Celsius: " + current.toCelsius());
System.out.println("Description: " + current.getDescription());
System.out.println("Comfortable? " + current.isComfortable());
// Print all temperatures with conversions
System.out.println("\nAll temperatures:");
for (Temperature t : Temperature.values()) {
System.out.printf("%s: %d°F = %.1f°C - %s%n",
t,
t.getFahrenheit(),
t.toCelsius(),
t.isComfortable() ? "✓" : "✗");
}
// Find comfortable temperatures
System.out.println("\nComfortable temperatures:");
for (Temperature t : Temperature.values()) {
if (t.isComfortable()) {
System.out.println(" " + t + ": " + t.getDescription());
}
}
// Compare temperatures
Temperature t1 = Temperature.COLD;
Temperature t2 = Temperature.HOT;
System.out.println("\nComparison:");
System.out.printf("%s (%d°F) vs %s (%d°F)%n",
t1, t1.getFahrenheit(),
t2, t2.getFahrenheit());
if (t1.getFahrenheit() < t2.getFahrenheit()) {
System.out.println(t1 + " is cooler");
}
}
}
Regular methods work with enum's fields. All constants share the method.
Complex enum
Full-featured enum with multiple fields and methods.
// Enum with multiple fields and complex logic
// Concept: complex enum - multiple fields and calculations
enum ShippingMethod {
STANDARD(5.99, 5, "5-7 business days"),
EXPRESS(12.99, 2, "2-3 business days"),
OVERNIGHT(24.99, 1, "Next business day"),
INTERNATIONAL(35.00, 10, "7-14 business days");
private final double baseCost;
private final int daysMin;
private final String description;
ShippingMethod(double baseCost, int daysMin, String description) {
this.baseCost = baseCost;
this.daysMin = daysMin;
this.description = description;
}
// Calculate cost with weight
public double calculateCost(double weightPounds) {
if (this == INTERNATIONAL) {
return baseCost + (weightPounds * 2.50);
} else if (this == OVERNIGHT) {
return baseCost + (weightPounds * 1.50);
} else {
return baseCost + (weightPounds * 0.50);
}
}
// Check if available for weight
public boolean isAvailableFor(double weightPounds) {
if (this == OVERNIGHT && weightPounds > 50) {
return false; // Overnight has weight limit
}
return true;
}
public double getBaseCost() { return baseCost; }
public String getDescription() { return description; }
public int getDaysMin() { return daysMin; }
}
public class ComplexEnum {
public static void main(String[] args) {
// Calculate shipping for different weights
double packageWeight = ;
System.out.println("Package weight: " + packageWeight + " lbs\n");
System.out.println("Shipping options:");
for (ShippingMethod method : ShippingMethod.values()) {
if (method.isAvailableFor(packageWeight)) {
double cost = method.calculateCost(packageWeight);
System.out.printf("%s: $%.2f (%s)%n",
method, cost, method.getDescription());
} else {
System.out.printf("%s: Not available for this weight%n", method);
}
}
// Find cheapest option
double weight = ;
ShippingMethod cheapest = ShippingMethod.STANDARD;
double lowestCost = cheapest.calculateCost(weight);
for (ShippingMethod method : ShippingMethod.values()) {
if (method.isAvailableFor(weight)) {
double cost = method.calculateCost(weight);
if (cost < lowestCost) {
cheapest = method;
lowestCost = cost;
}
}
}
System.out.printf("\nFor %.1f lbs, cheapest: %s ($%.2f)%n",
weight, cheapest, lowestCost);
// Find fastest under budget
double budget = 15.00;
ShippingMethod fastest = null;
for (ShippingMethod method : ShippingMethod.values()) {
double cost = method.calculateCost(weight);
if (cost <= budget) {
if (fastest == null || method.getDaysMin() < fastest.getDaysMin()) {
fastest = method;
}
}
}
if (fastest != null) {
System.out.printf("Budget $%.2f: %s (%.0f days, $%.2f)%n",
budget, fastest,
(double)fastest.getDaysMin(),
fastest.calculateCost(weight));
}
}
}
// Enum with multiple fields and complex logic
// Concept: complex enum - multiple fields and calculations
enum ShippingMethod {
STANDARD(5.99, 5, "5-7 business days"),
EXPRESS(12.99, 2, "2-3 business days"),
OVERNIGHT(24.99, 1, "Next business day"),
INTERNATIONAL(35.00, 10, "7-14 business days");
private final double baseCost;
private final int daysMin;
private final String description;
ShippingMethod(double baseCost, int daysMin, String description) {
this.baseCost = baseCost;
this.daysMin = daysMin;
this.description = description;
}
// Calculate cost with weight
public double calculateCost(double weightPounds) {
if (this == INTERNATIONAL) {
return baseCost + (weightPounds * 2.50);
} else if (this == OVERNIGHT) {
return baseCost + (weightPounds * 1.50);
} else {
return baseCost + (weightPounds * 0.50);
}
}
// Check if available for weight
public boolean isAvailableFor(double weightPounds) {
if (this == OVERNIGHT && weightPounds > 50) {
return false; // Overnight has weight limit
}
return true;
}
public double getBaseCost() { return baseCost; }
public String getDescription() { return description; }
public int getDaysMin() { return daysMin; }
}
public class ComplexEnum {
public static void main(String[] args) {
// Calculate shipping for different weights
double packageWeight = ;
System.out.println("Package weight: " + packageWeight + " lbs\n");
System.out.println("Shipping options:");
for (ShippingMethod method : ShippingMethod.values()) {
if (method.isAvailableFor(packageWeight)) {
double cost = method.calculateCost(packageWeight);
System.out.printf("%s: $%.2f (%s)%n",
method, cost, method.getDescription());
} else {
System.out.printf("%s: Not available for this weight%n", method);
}
}
// Find cheapest option
double weight = ;
ShippingMethod cheapest = ShippingMethod.STANDARD;
double lowestCost = cheapest.calculateCost(weight);
for (ShippingMethod method : ShippingMethod.values()) {
if (method.isAvailableFor(weight)) {
double cost = method.calculateCost(weight);
if (cost < lowestCost) {
cheapest = method;
lowestCost = cost;
}
}
}
System.out.printf("\nFor %.1f lbs, cheapest: %s ($%.2f)%n",
weight, cheapest, lowestCost);
// Find fastest under budget
double budget = 15.00;
ShippingMethod fastest = null;
for (ShippingMethod method : ShippingMethod.values()) {
double cost = method.calculateCost(weight);
if (cost <= budget) {
if (fastest == null || method.getDaysMin() < fastest.getDaysMin()) {
fastest = method;
}
}
}
if (fastest != null) {
System.out.printf("Budget $%.2f: %s (%.0f days, $%.2f)%n",
budget, fastest,
(double)fastest.getDaysMin(),
fastest.calculateCost(weight));
}
}
}
// Enum with multiple fields and complex logic
// Concept: complex enum - multiple fields and calculations
enum ShippingMethod {
STANDARD(5.99, 5, "5-7 business days"),
EXPRESS(12.99, 2, "2-3 business days"),
OVERNIGHT(24.99, 1, "Next business day"),
INTERNATIONAL(35.00, 10, "7-14 business days");
private final double baseCost;
private final int daysMin;
private final String description;
ShippingMethod(double baseCost, int daysMin, String description) {
this.baseCost = baseCost;
this.daysMin = daysMin;
this.description = description;
}
// Calculate cost with weight
public double calculateCost(double weightPounds) {
if (this == INTERNATIONAL) {
return baseCost + (weightPounds * 2.50);
} else if (this == OVERNIGHT) {
return baseCost + (weightPounds * 1.50);
} else {
return baseCost + (weightPounds * 0.50);
}
}
// Check if available for weight
public boolean isAvailableFor(double weightPounds) {
if (this == OVERNIGHT && weightPounds > 50) {
return false; // Overnight has weight limit
}
return true;
}
public double getBaseCost() { return baseCost; }
public String getDescription() { return description; }
public int getDaysMin() { return daysMin; }
}
public class ComplexEnum {
public static void main(String[] args) {
// Calculate shipping for different weights
double packageWeight = ;
System.out.println("Package weight: " + packageWeight + " lbs\n");
System.out.println("Shipping options:");
for (ShippingMethod method : ShippingMethod.values()) {
if (method.isAvailableFor(packageWeight)) {
double cost = method.calculateCost(packageWeight);
System.out.printf("%s: $%.2f (%s)%n",
method, cost, method.getDescription());
} else {
System.out.printf("%s: Not available for this weight%n", method);
}
}
// Find cheapest option
double weight = ;
ShippingMethod cheapest = ShippingMethod.STANDARD;
double lowestCost = cheapest.calculateCost(weight);
for (ShippingMethod method : ShippingMethod.values()) {
if (method.isAvailableFor(weight)) {
double cost = method.calculateCost(weight);
if (cost < lowestCost) {
cheapest = method;
lowestCost = cost;
}
}
}
System.out.printf("\nFor %.1f lbs, cheapest: %s ($%.2f)%n",
weight, cheapest, lowestCost);
// Find fastest under budget
double budget = 15.00;
ShippingMethod fastest = null;
for (ShippingMethod method : ShippingMethod.values()) {
double cost = method.calculateCost(weight);
if (cost <= budget) {
if (fastest == null || method.getDaysMin() < fastest.getDaysMin()) {
fastest = method;
}
}
}
if (fastest != null) {
System.out.printf("Budget $%.2f: %s (%.0f days, $%.2f)%n",
budget, fastest,
(double)fastest.getDaysMin(),
fastest.calculateCost(weight));
}
}
}
// Enum with multiple fields and complex logic
// Concept: complex enum - multiple fields and calculations
enum ShippingMethod {
STANDARD(5.99, 5, "5-7 business days"),
EXPRESS(12.99, 2, "2-3 business days"),
OVERNIGHT(24.99, 1, "Next business day"),
INTERNATIONAL(35.00, 10, "7-14 business days");
private final double baseCost;
private final int daysMin;
private final String description;
ShippingMethod(double baseCost, int daysMin, String description) {
this.baseCost = baseCost;
this.daysMin = daysMin;
this.description = description;
}
// Calculate cost with weight
public double calculateCost(double weightPounds) {
if (this == INTERNATIONAL) {
return baseCost + (weightPounds * 2.50);
} else if (this == OVERNIGHT) {
return baseCost + (weightPounds * 1.50);
} else {
return baseCost + (weightPounds * 0.50);
}
}
// Check if available for weight
public boolean isAvailableFor(double weightPounds) {
if (this == OVERNIGHT && weightPounds > 50) {
return false; // Overnight has weight limit
}
return true;
}
public double getBaseCost() { return baseCost; }
public String getDescription() { return description; }
public int getDaysMin() { return daysMin; }
}
public class ComplexEnum {
public static void main(String[] args) {
// Calculate shipping for different weights
double packageWeight = ;
System.out.println("Package weight: " + packageWeight + " lbs\n");
System.out.println("Shipping options:");
for (ShippingMethod method : ShippingMethod.values()) {
if (method.isAvailableFor(packageWeight)) {
double cost = method.calculateCost(packageWeight);
System.out.printf("%s: $%.2f (%s)%n",
method, cost, method.getDescription());
} else {
System.out.printf("%s: Not available for this weight%n", method);
}
}
// Find cheapest option
double weight = ;
ShippingMethod cheapest = ShippingMethod.STANDARD;
double lowestCost = cheapest.calculateCost(weight);
for (ShippingMethod method : ShippingMethod.values()) {
if (method.isAvailableFor(weight)) {
double cost = method.calculateCost(weight);
if (cost < lowestCost) {
cheapest = method;
lowestCost = cost;
}
}
}
System.out.printf("\nFor %.1f lbs, cheapest: %s ($%.2f)%n",
weight, cheapest, lowestCost);
// Find fastest under budget
double budget = 15.00;
ShippingMethod fastest = null;
for (ShippingMethod method : ShippingMethod.values()) {
double cost = method.calculateCost(weight);
if (cost <= budget) {
if (fastest == null || method.getDaysMin() < fastest.getDaysMin()) {
fastest = method;
}
}
}
if (fastest != null) {
System.out.printf("Budget $%.2f: %s (%.0f days, $%.2f)%n",
budget, fastest,
(double)fastest.getDaysMin(),
fastest.calculateCost(weight));
}
}
}
// Enum with multiple fields and complex logic
// Concept: complex enum - multiple fields and calculations
enum ShippingMethod {
STANDARD(5.99, 5, "5-7 business days"),
EXPRESS(12.99, 2, "2-3 business days"),
OVERNIGHT(24.99, 1, "Next business day"),
INTERNATIONAL(35.00, 10, "7-14 business days");
private final double baseCost;
private final int daysMin;
private final String description;
ShippingMethod(double baseCost, int daysMin, String description) {
this.baseCost = baseCost;
this.daysMin = daysMin;
this.description = description;
}
// Calculate cost with weight
public double calculateCost(double weightPounds) {
if (this == INTERNATIONAL) {
return baseCost + (weightPounds * 2.50);
} else if (this == OVERNIGHT) {
return baseCost + (weightPounds * 1.50);
} else {
return baseCost + (weightPounds * 0.50);
}
}
// Check if available for weight
public boolean isAvailableFor(double weightPounds) {
if (this == OVERNIGHT && weightPounds > 50) {
return false; // Overnight has weight limit
}
return true;
}
public double getBaseCost() { return baseCost; }
public String getDescription() { return description; }
public int getDaysMin() { return daysMin; }
}
public class ComplexEnum {
public static void main(String[] args) {
// Calculate shipping for different weights
double packageWeight = ;
System.out.println("Package weight: " + packageWeight + " lbs\n");
System.out.println("Shipping options:");
for (ShippingMethod method : ShippingMethod.values()) {
if (method.isAvailableFor(packageWeight)) {
double cost = method.calculateCost(packageWeight);
System.out.printf("%s: $%.2f (%s)%n",
method, cost, method.getDescription());
} else {
System.out.printf("%s: Not available for this weight%n", method);
}
}
// Find cheapest option
double weight = ;
ShippingMethod cheapest = ShippingMethod.STANDARD;
double lowestCost = cheapest.calculateCost(weight);
for (ShippingMethod method : ShippingMethod.values()) {
if (method.isAvailableFor(weight)) {
double cost = method.calculateCost(weight);
if (cost < lowestCost) {
cheapest = method;
lowestCost = cost;
}
}
}
System.out.printf("\nFor %.1f lbs, cheapest: %s ($%.2f)%n",
weight, cheapest, lowestCost);
// Find fastest under budget
double budget = 15.00;
ShippingMethod fastest = null;
for (ShippingMethod method : ShippingMethod.values()) {
double cost = method.calculateCost(weight);
if (cost <= budget) {
if (fastest == null || method.getDaysMin() < fastest.getDaysMin()) {
fastest = method;
}
}
}
if (fastest != null) {
System.out.printf("Budget $%.2f: %s (%.0f days, $%.2f)%n",
budget, fastest,
(double)fastest.getDaysMin(),
fastest.calculateCost(weight));
}
}
}
// Enum with multiple fields and complex logic
// Concept: complex enum - multiple fields and calculations
enum ShippingMethod {
STANDARD(5.99, 5, "5-7 business days"),
EXPRESS(12.99, 2, "2-3 business days"),
OVERNIGHT(24.99, 1, "Next business day"),
INTERNATIONAL(35.00, 10, "7-14 business days");
private final double baseCost;
private final int daysMin;
private final String description;
ShippingMethod(double baseCost, int daysMin, String description) {
this.baseCost = baseCost;
this.daysMin = daysMin;
this.description = description;
}
// Calculate cost with weight
public double calculateCost(double weightPounds) {
if (this == INTERNATIONAL) {
return baseCost + (weightPounds * 2.50);
} else if (this == OVERNIGHT) {
return baseCost + (weightPounds * 1.50);
} else {
return baseCost + (weightPounds * 0.50);
}
}
// Check if available for weight
public boolean isAvailableFor(double weightPounds) {
if (this == OVERNIGHT && weightPounds > 50) {
return false; // Overnight has weight limit
}
return true;
}
public double getBaseCost() { return baseCost; }
public String getDescription() { return description; }
public int getDaysMin() { return daysMin; }
}
public class ComplexEnum {
public static void main(String[] args) {
// Calculate shipping for different weights
double packageWeight = ;
System.out.println("Package weight: " + packageWeight + " lbs\n");
System.out.println("Shipping options:");
for (ShippingMethod method : ShippingMethod.values()) {
if (method.isAvailableFor(packageWeight)) {
double cost = method.calculateCost(packageWeight);
System.out.printf("%s: $%.2f (%s)%n",
method, cost, method.getDescription());
} else {
System.out.printf("%s: Not available for this weight%n", method);
}
}
// Find cheapest option
double weight = ;
ShippingMethod cheapest = ShippingMethod.STANDARD;
double lowestCost = cheapest.calculateCost(weight);
for (ShippingMethod method : ShippingMethod.values()) {
if (method.isAvailableFor(weight)) {
double cost = method.calculateCost(weight);
if (cost < lowestCost) {
cheapest = method;
lowestCost = cost;
}
}
}
System.out.printf("\nFor %.1f lbs, cheapest: %s ($%.2f)%n",
weight, cheapest, lowestCost);
// Find fastest under budget
double budget = 15.00;
ShippingMethod fastest = null;
for (ShippingMethod method : ShippingMethod.values()) {
double cost = method.calculateCost(weight);
if (cost <= budget) {
if (fastest == null || method.getDaysMin() < fastest.getDaysMin()) {
fastest = method;
}
}
}
if (fastest != null) {
System.out.printf("Budget $%.2f: %s (%.0f days, $%.2f)%n",
budget, fastest,
(double)fastest.getDaysMin(),
fastest.calculateCost(weight));
}
}
}
Combine fields, constructors, methods - enum as a full data type.
Abstract methods per constant
Each constant provides its own implementation.
// Enum with abstract methods (per-constant behavior)
// Concept: abstract method in enum
// Concept: per-constant behavior
enum Operation {
PLUS("+") {
@Override
public double apply(double x, double y) {
return x + y;
}
},
MINUS("-") {
@Override
public double apply(double x, double y) {
return x - y;
}
},
MULTIPLY("*") {
@Override
public double apply(double x, double y) {
return x * y;
}
},
DIVIDE("/") {
@Override
public double apply(double x, double y) {
return x / y;
}
};
private final String symbol;
Operation(String symbol) {
this.symbol = symbol;
}
// Abstract method - each constant must implement
public abstract double apply(double x, double y);
public String getSymbol() {
return symbol;
}
}
public class AbstractMethod {
public static void main(String[] args) {
// Use operations
double a = 10;
double b = 3;
System.out.println("Calculate: a=" + a + ", b=" + b + "\n");
for (Operation op : Operation.values()) {
double result = op.apply(a, b);
System.out.printf("%s %s %s = %.2f%n",
a, op.getSymbol(), b, result);
}
// Build calculator
Operation operator = ;
double x = 7;
double y = 6;
double answer = operator.apply(x, y);
System.out.printf("\n%.0f %s %.0f = %.0f%n",
x, operator.getSymbol(), y, answer);
// Evaluate expressions
class Expression {
double left;
Operation op;
double right;
Expression(double left, Operation op, double right) {
this.left = left;
this.op = op;
this.right = right;
}
double evaluate() {
return op.apply(left, right);
}
public String toString() {
return String.format("%.0f %s %.0f = %.2f",
left, op.getSymbol(), right, evaluate());
}
}
Expression[] expressions = {
new Expression(100, Operation.PLUS, 50),
new Expression(100, Operation.MINUS, 50),
new Expression(100, Operation.MULTIPLY, 50),
new Expression(100, Operation.DIVIDE, 50)
};
System.out.println("\nExpressions:");
for (Expression expr : expressions) {
System.out.println(" " + expr);
}
}
}
// Enum with abstract methods (per-constant behavior)
// Concept: abstract method in enum
// Concept: per-constant behavior
enum Operation {
PLUS("+") {
@Override
public double apply(double x, double y) {
return x + y;
}
},
MINUS("-") {
@Override
public double apply(double x, double y) {
return x - y;
}
},
MULTIPLY("*") {
@Override
public double apply(double x, double y) {
return x * y;
}
},
DIVIDE("/") {
@Override
public double apply(double x, double y) {
return x / y;
}
};
private final String symbol;
Operation(String symbol) {
this.symbol = symbol;
}
// Abstract method - each constant must implement
public abstract double apply(double x, double y);
public String getSymbol() {
return symbol;
}
}
public class AbstractMethod {
public static void main(String[] args) {
// Use operations
double a = 10;
double b = 3;
System.out.println("Calculate: a=" + a + ", b=" + b + "\n");
for (Operation op : Operation.values()) {
double result = op.apply(a, b);
System.out.printf("%s %s %s = %.2f%n",
a, op.getSymbol(), b, result);
}
// Build calculator
Operation operator = ;
double x = 7;
double y = 6;
double answer = operator.apply(x, y);
System.out.printf("\n%.0f %s %.0f = %.0f%n",
x, operator.getSymbol(), y, answer);
// Evaluate expressions
class Expression {
double left;
Operation op;
double right;
Expression(double left, Operation op, double right) {
this.left = left;
this.op = op;
this.right = right;
}
double evaluate() {
return op.apply(left, right);
}
public String toString() {
return String.format("%.0f %s %.0f = %.2f",
left, op.getSymbol(), right, evaluate());
}
}
Expression[] expressions = {
new Expression(100, Operation.PLUS, 50),
new Expression(100, Operation.MINUS, 50),
new Expression(100, Operation.MULTIPLY, 50),
new Expression(100, Operation.DIVIDE, 50)
};
System.out.println("\nExpressions:");
for (Expression expr : expressions) {
System.out.println(" " + expr);
}
}
}
// Enum with abstract methods (per-constant behavior)
// Concept: abstract method in enum
// Concept: per-constant behavior
enum Operation {
PLUS("+") {
@Override
public double apply(double x, double y) {
return x + y;
}
},
MINUS("-") {
@Override
public double apply(double x, double y) {
return x - y;
}
},
MULTIPLY("*") {
@Override
public double apply(double x, double y) {
return x * y;
}
},
DIVIDE("/") {
@Override
public double apply(double x, double y) {
return x / y;
}
};
private final String symbol;
Operation(String symbol) {
this.symbol = symbol;
}
// Abstract method - each constant must implement
public abstract double apply(double x, double y);
public String getSymbol() {
return symbol;
}
}
public class AbstractMethod {
public static void main(String[] args) {
// Use operations
double a = 10;
double b = 3;
System.out.println("Calculate: a=" + a + ", b=" + b + "\n");
for (Operation op : Operation.values()) {
double result = op.apply(a, b);
System.out.printf("%s %s %s = %.2f%n",
a, op.getSymbol(), b, result);
}
// Build calculator
Operation operator = ;
double x = 7;
double y = 6;
double answer = operator.apply(x, y);
System.out.printf("\n%.0f %s %.0f = %.0f%n",
x, operator.getSymbol(), y, answer);
// Evaluate expressions
class Expression {
double left;
Operation op;
double right;
Expression(double left, Operation op, double right) {
this.left = left;
this.op = op;
this.right = right;
}
double evaluate() {
return op.apply(left, right);
}
public String toString() {
return String.format("%.0f %s %.0f = %.2f",
left, op.getSymbol(), right, evaluate());
}
}
Expression[] expressions = {
new Expression(100, Operation.PLUS, 50),
new Expression(100, Operation.MINUS, 50),
new Expression(100, Operation.MULTIPLY, 50),
new Expression(100, Operation.DIVIDE, 50)
};
System.out.println("\nExpressions:");
for (Expression expr : expressions) {
System.out.println(" " + expr);
}
}
}
abstract method in enum - each constant implements differently.
Enum implementing interface
Enums can implement interfaces.
// Enum implementing interface
// Concept: enum implements interface
// Concept: polymorphism with enum
interface Describable {
String getDescription();
String getDetails();
}
// Enum implementing interface
enum HttpStatus implements Describable {
OK(200, "Success"),
CREATED(201, "Resource created"),
BAD_REQUEST(400, "Invalid request"),
NOT_FOUND(404, "Resource not found"),
SERVER_ERROR(500, "Internal error");
private final int code;
private final String message;
HttpStatus(int code, String message) {
this.code = code;
this.message = message;
}
// Implement interface methods
@Override
public String getDescription() {
return code + " " + name();
}
@Override
public String getDetails() {
return message;
}
// Enum-specific methods
public int getCode() {
return code;
}
public boolean isSuccess() {
return code >= 200 && code < 300;
}
public boolean isError() {
return code >= 400;
}
}
public class ImplementingInterface {
public static void main(String[] args) {
// Use enum as interface type
Describable status = HttpStatus.OK;
System.out.println("Description: " + status.getDescription());
System.out.println("Details: " + status.getDetails());
// Check status types
HttpStatus[] responses = {
HttpStatus.OK,
HttpStatus.NOT_FOUND,
HttpStatus.SERVER_ERROR,
HttpStatus.CREATED
};
System.out.println("\nAnalyzing responses:");
for (HttpStatus resp : responses) {
String type = resp.isSuccess() ? "SUCCESS" :
resp.isError() ? "ERROR" : "INFO";
System.out.printf("%d %s: %s [%s]%n",
resp.getCode(),
resp.name(),
resp.getDetails(),
type);
}
// Polymorphic processing
System.out.println("\nPolymorphic usage:");
printDescribable(HttpStatus.BAD_REQUEST);
// Filter by criteria
System.out.println("\nError statuses:");
for (HttpStatus s : HttpStatus.values()) {
if (s.isError()) {
System.out.println(" " + s.getDescription());
}
}
System.out.println("\nSuccess statuses:");
for (HttpStatus s : HttpStatus.values()) {
if (s.isSuccess()) {
System.out.println(" " + s.getDescription());
}
}
// Find by code
int searchCode = ;
HttpStatus found = null;
for (HttpStatus s : HttpStatus.values()) {
if (s.getCode() == searchCode) {
found = s;
break;
}
}
if (found != null) {
System.out.println("\nCode " + searchCode + ": " + found.getDetails());
}
}
static void printDescribable(Describable d) {
System.out.println(" " + d.getDescription());
System.out.println(" " + d.getDetails());
}
}
// Enum implementing interface
// Concept: enum implements interface
// Concept: polymorphism with enum
interface Describable {
String getDescription();
String getDetails();
}
// Enum implementing interface
enum HttpStatus implements Describable {
OK(200, "Success"),
CREATED(201, "Resource created"),
BAD_REQUEST(400, "Invalid request"),
NOT_FOUND(404, "Resource not found"),
SERVER_ERROR(500, "Internal error");
private final int code;
private final String message;
HttpStatus(int code, String message) {
this.code = code;
this.message = message;
}
// Implement interface methods
@Override
public String getDescription() {
return code + " " + name();
}
@Override
public String getDetails() {
return message;
}
// Enum-specific methods
public int getCode() {
return code;
}
public boolean isSuccess() {
return code >= 200 && code < 300;
}
public boolean isError() {
return code >= 400;
}
}
public class ImplementingInterface {
public static void main(String[] args) {
// Use enum as interface type
Describable status = HttpStatus.OK;
System.out.println("Description: " + status.getDescription());
System.out.println("Details: " + status.getDetails());
// Check status types
HttpStatus[] responses = {
HttpStatus.OK,
HttpStatus.NOT_FOUND,
HttpStatus.SERVER_ERROR,
HttpStatus.CREATED
};
System.out.println("\nAnalyzing responses:");
for (HttpStatus resp : responses) {
String type = resp.isSuccess() ? "SUCCESS" :
resp.isError() ? "ERROR" : "INFO";
System.out.printf("%d %s: %s [%s]%n",
resp.getCode(),
resp.name(),
resp.getDetails(),
type);
}
// Polymorphic processing
System.out.println("\nPolymorphic usage:");
printDescribable(HttpStatus.BAD_REQUEST);
// Filter by criteria
System.out.println("\nError statuses:");
for (HttpStatus s : HttpStatus.values()) {
if (s.isError()) {
System.out.println(" " + s.getDescription());
}
}
System.out.println("\nSuccess statuses:");
for (HttpStatus s : HttpStatus.values()) {
if (s.isSuccess()) {
System.out.println(" " + s.getDescription());
}
}
// Find by code
int searchCode = ;
HttpStatus found = null;
for (HttpStatus s : HttpStatus.values()) {
if (s.getCode() == searchCode) {
found = s;
break;
}
}
if (found != null) {
System.out.println("\nCode " + searchCode + ": " + found.getDetails());
}
}
static void printDescribable(Describable d) {
System.out.println(" " + d.getDescription());
System.out.println(" " + d.getDetails());
}
}
// Enum implementing interface
// Concept: enum implements interface
// Concept: polymorphism with enum
interface Describable {
String getDescription();
String getDetails();
}
// Enum implementing interface
enum HttpStatus implements Describable {
OK(200, "Success"),
CREATED(201, "Resource created"),
BAD_REQUEST(400, "Invalid request"),
NOT_FOUND(404, "Resource not found"),
SERVER_ERROR(500, "Internal error");
private final int code;
private final String message;
HttpStatus(int code, String message) {
this.code = code;
this.message = message;
}
// Implement interface methods
@Override
public String getDescription() {
return code + " " + name();
}
@Override
public String getDetails() {
return message;
}
// Enum-specific methods
public int getCode() {
return code;
}
public boolean isSuccess() {
return code >= 200 && code < 300;
}
public boolean isError() {
return code >= 400;
}
}
public class ImplementingInterface {
public static void main(String[] args) {
// Use enum as interface type
Describable status = HttpStatus.OK;
System.out.println("Description: " + status.getDescription());
System.out.println("Details: " + status.getDetails());
// Check status types
HttpStatus[] responses = {
HttpStatus.OK,
HttpStatus.NOT_FOUND,
HttpStatus.SERVER_ERROR,
HttpStatus.CREATED
};
System.out.println("\nAnalyzing responses:");
for (HttpStatus resp : responses) {
String type = resp.isSuccess() ? "SUCCESS" :
resp.isError() ? "ERROR" : "INFO";
System.out.printf("%d %s: %s [%s]%n",
resp.getCode(),
resp.name(),
resp.getDetails(),
type);
}
// Polymorphic processing
System.out.println("\nPolymorphic usage:");
printDescribable(HttpStatus.BAD_REQUEST);
// Filter by criteria
System.out.println("\nError statuses:");
for (HttpStatus s : HttpStatus.values()) {
if (s.isError()) {
System.out.println(" " + s.getDescription());
}
}
System.out.println("\nSuccess statuses:");
for (HttpStatus s : HttpStatus.values()) {
if (s.isSuccess()) {
System.out.println(" " + s.getDescription());
}
}
// Find by code
int searchCode = ;
HttpStatus found = null;
for (HttpStatus s : HttpStatus.values()) {
if (s.getCode() == searchCode) {
found = s;
break;
}
}
if (found != null) {
System.out.println("\nCode " + searchCode + ": " + found.getDetails());
}
}
static void printDescribable(Describable d) {
System.out.println(" " + d.getDescription());
System.out.println(" " + d.getDetails());
}
}
enum Name implements Interface - enum provides interface methods.
Exercise: Practical.java
Build an operation enum (ADD, SUBTRACT, MULTIPLY, DIVIDE)