Skip to main content

6. Array and Enum

 

Array Declarations

  • Arrays are objects that store multiple variables of the same type, or variables that are all subclasses of the same type.
  • Arrays can hold either primitives or object references, but the array itself will always be an object on the heap, even if the array is declared to hold primitive elements.
  • Arrays are declared by stating the type of elements the array will hold, followed by square brackets to either side of an identifier.
  • class Array {
        int a[];
        double[] b;
        char[] c[];
        String[][] d;
        Short e[][];
    }

  • It is never legal to include the size of the array in our declaration. The JVM doesn't allocate space until we actually instantiate the array object.

Enum Declarations

  • An enum specifies a list of constant values assigned to a type.
  • An enum is not a String or an int; an enum constant's type is the enum type.
  • Enums can be declared as their own separate class, or a class member or within a method.
  • The syntax for accessing an enum's members depends on where the enum was declared.
  • An enum is a special kind of class, we can do more than just list the enumerated values.
  • We can add constructors, instance variables, methods, and something really strange known as a constant specific class body.
  • enum DeviceState {
        ON(1), OFF(0);

        private int state;

        DeviceState(int state) {
            this.state = state;
        }

        public int getState() {
            return state;
        }
    }

    class Devices {
        DeviceState state;

        public static void main(String[] args) {
            Devices fan = new Devices();
            fan.state = DeviceState.OFF;
            System.out.println("FAN is: " + fan.state);
            System.out.println("State of FAN is: " + fan.state.getState());
            for (DeviceState state : DeviceState.values()) {
                System.out.println(state + " " + state.getState());
            }
        }
    }

  • We can NEVER invoke an enum constructor directly. The enum constructor is invoked automatically, with the arguments we define after the constant value.
  • We can define more than one argument to the constructor, and we can overload the enum constructor.
Prev Next

Comments