English Cathedrals (Enums)
Christianity had arrived in Britain long before the Norman invasion. However, just like their penchant for building castles of stone, the Normans had a desire to build massive, stone cathedrals. Since they were made of stone, many of these cathedrals have survived to modern times and are still in use.
Java provides you with many variable types. Some examples are strings, ints, and doubles. But you can also create your own variable types using enums. You create enums to group things that have a common purpose. For example: enums can be used to group directions.
Here is the code to group directions into an enum.
- import static java.lang.System.out;
- public enum Direction {
- NORTH, SOUTH, EAST, WEST, NORTHEAST, SOUTHEAST, NORTHWEST, SOUTHWEST
- }
Here is code that creates a constructor that uses the variable type established by the enum class.
- import static java.lang.System.out;
- // The (Direction loc) variable declaration shown below uses
- // the enum established in the file Direction.java.
- class CathedralConstructor {
- String name;
- Direction loc;
- // (Direction location) in the parameter parenthesis () below
- // establishes that "location" will accept a value of type Direction.
- CathedralConstructor(String name, Direction location) {
- this.name = name;
- loc = location;
- }
- /*
- * Notice the "this" keyword in the above line.
- * When you use the "this" keyword you specify that
- * the first variable in the element is the class variable.
- */
- public void display() {
- out.println();
- out.println("Cathedral Name: " + name);
- out.println("Cathedral Location: " + loc);
- }
- }
Here is code that creates a calling class for the CathedralConstructor.
- import static java.lang.System.out;
- public class UseCathedralConstructor {
- public static void main(String[] args) {
- CathedralConstructor t1 = new CathedralConstructor("Durham Cathedral", Direction.NORTH);
- CathedralConstructor t2 = new CathedralConstructor("Petersborough Cathedral", Direction.NORTH);
- CathedralConstructor t3 = new CathedralConstructor("Canterbury Cathedral", Direction.SOUTHEAST);
- CathedralConstructor t4 = new CathedralConstructor("Gloucester Cathedral", Direction.WEST);
- t1.display();
- t2.display();
- t3.display();
- t4.display();
- }
- }
Use Save As to save the code files to your folder. Then compile the code files in the Command prompt window. Run the UseCathedralConstructor.java class.
Your output should look like this:
c:\javamike>java UseCathedralConstructor
Cathedral Name: Durham Cathedral
Cathedral Location: NORTH
Cathedral Name: Petersborough Cathedral
Cathedral Location: NORTH
Cathedral Name: Canterbury Cathedral
Cathedral Location: SOUTHEAST
Cathedral Name: Gloucester Cathedral
Cathedral Location: WEST