Play around with Enum

Enum is a new Java SE 5 features. It seem likes able to declare a new type, with limited specified value. Below is the demonstration of Enum.

enum Car {
    TOYOTA (30000,1000,"BIG"),
    CAMRY (100000,200,"BIG") {
        public int totalPrice() {
            return price * unit + 1500;
        }
    },
    PROTON (10000,5000,"MEDIUM");

    final int price;
    final int unit;
    final String size;

    Car(int price, int unit, String size) {
        this.price = price;
        this.unit = unit;
        this.size = size;
    }

    public int getPrice() { return price; }
    public int getUnit() { return unit; }
    public String getSize() { return size; }

    public int totalPrice() {
        return price * unit;
    }

    public String toString() {
        return "PRICE: " + price + "\tUNIT: " + unit + "\tSIZE: " + size;
    }
}

public class EnumPlay {
    public static void main(String args[]) {
        Car c1 = Car.TOYOTA;
        Car c2 = Car.CAMRY;
        Car c3 = Car.PROTON;

        for(Car c : Car.values()) {
            System.out.println(c.name()+ "\n" + c + "\nTotal: " + c.totalPrice() + "\n");
        }

        System.out.println("Split it up:");
        System.out.println(c1.name() + " has " + c1.getUnit() + " cars. Each price costs " + c1.getPrice() + ". But somehow it is " + c1.getSize().toLowerCase());
        System.out.println(c2.name() + " has " + c2.getUnit() + " cars. Each price costs " + c2.getPrice() + ". But somehow it is " + c2.getSize().toLowerCase());
        System.out.println(c3.name() + " has " + c3.getUnit() + " cars. Each price costs " + c3.getPrice() + ". But somehow it is " + c3.getSize().toLowerCase());
    }
}

Java Enum Tutorial

Author: fyhao

Jebsen & Jessen Comms Singapore INTI University College Bsc (Hon) of Computer Science, Coventry University

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.