Enumeration Types - PowerPoint PPT Presentation

1 / 46
About This Presentation
Title:

Enumeration Types

Description:

The only literal of object reference is null. It can be used anywhere a reference is expected ... For example: 0x12p0 0x1.2p4 0x.12P 8 0x120p-4 ... – PowerPoint PPT presentation

Number of Views:33
Avg rating:3.0/5.0
Slides: 47
Provided by: ebizUa
Category:

less

Transcript and Presenter's Notes

Title: Enumeration Types


1
Java Programming
  • CHAPTER 6, 7, 8
  • Enumeration Types
  • Tokens, Values, and Variables
  • Primitives as Types

2
Contents
  • Enumeration Types
  • Tokens, Values, and Variables
  • Lexical elements
  • Types and literals
  • Variables and array variables
  • The meanings of names
  • Primitives as Types
  • Common fields and methods
  • Void, Boolean, Number, and Character
  • Boxing conversions

3
Enumeration Types
  • Also known as enumerated types, or simply enum
  • In Java an enum is a special kind of class
  • It has an instance that represents each value of
    the enum
  • An enum is a type that has all values (i.e.
    static constants) immediately defined
  • enum Suit
  • CLUBS,
  • DIAMONDS,
  • HEARTS,
  • SPADES,
  • Suit currentSuit Suit.SPADES
  • if (currentSuit Suit.CLUBS)
  • Suit aSuit ? new Suit() // error

body consists of static fields
optional
4
Enum Declarations
  • All enums implicitly extend Enum
  • All enums are assumed final
  • An enum can declare to implement interfaces
  • import java.lang.Enum
  • enum Suit extends Enum
  • CLUBS,
  • DIAMONDS,
  • HEARTS,
  • SPADES
  • public static int getSize()
  • return 4
  • String name Suit.CLUBS.name()
  • ? CLUBS

5
Enum Structure
  • An enum can define, just as a class, fields,
    methods, and nested types, including nested
    enums
  • The enum constants are static firlds with the
    same type as the enum
  • Every enum has 2 static methods
  • public static E values() returns an array
    containing each of the enum constants in the
    order declared
  • public static E valueOf(String name) return the
    enum constant with the given name

6
Enum Modifiers
  • An enum declaration can be proceeded by certain
    modifiers
  • annotations
  • access modifiers a top level enum is either
    public, or accessible within its package
  • static all nested enums are implicitly static
  • An enum cannot be
  • declared abstract because it cannot be extended
  • declared final but it acts as if final

7
Enum Constant Declarations
  • The simplest enum constant declaration is to give
    a name to it
  • They are implicitly public, static, and final
    fields
  • They have the same type as the enum
  • An enum constant declaration cannot have
    modifiers applied to it, except for annotations

8
Construction
  • An enum can declare constructors
  • A constructor is selected based on the arguments
  • The get/set name functionality is already built
    in
  • By invoking the String name() method on an enum
    constant returns its name as a String
  • enum Suit
  • CLUBS(CLUBS),
  • DIAMONDS(DIAMONDS),
  • HEARTS(HEARTS),
  • SPADES(SPADES)
  • String name
  • Suit(String name)
  • this.name name
  • public String toString()
  • return name
  • String name Suit.CLUBS.name()

9
Internal Definition
  • This pseudo code shows a mock class definition
    for the Suit enum
  • 3 restrictions on enum constructors
  • All enum constructors are private to ensure that
    an enum cannot be instantiated directly
  • The constructor cannot explicitly invoke a
    superclass constructor
  • An enum constructor cannot use a nonconstant
    static field of the enum
  • class Suit extends EnumltSuitgt implements
    ComparableltSuitgt, Serializable
  • public static final Suit CLUBS new
    Suit(CLUBS)
  • public static final Suit DIAMONDS new
    Suit(DIAMONDS)
  • String name
  • static String prefix Suit.
  • Suit(String name)
  • this.name prefix name // error
  • public String toString()
  • return name

1st
2nd
10
Constant Specific Behavior
  • Enum constants may have a state that is set by a
    constructor and accessed with a method
  • Constant-specific-behavior varies between the
    different enum constants
  • The classes defined for each enum are effectively
    anonymous inner classes
  • These classes can define fields and methods, but
    no constructors or static members
  • Enums can declare abstract methods but each enum
    constant must implement it
  • enum ChessPiece PAWN, ROOK
  • class ChessRules
  • SetltPositiongt reachable(ChessPiece cp, Position
    current)
  • if (cp ChessPiece.PAWN)
  • return pawnReachable(current)
  • else if (cp ChessPiece.ROOK)
  • return rookReachable(current)
  • else
  • return null
  • enum ChessPiece
  • PAWN
  • SetltPositiongt reachable(Poisition current)
  • return ChessRules.pawnReachable(current)
  • ,
  • ROOK
  • SetltPositiongt reachable(Poisition current)

11
To Enum or Not
  • Enums are constants that can have a state and
    behavior, but cannot be extended
  • Enum constants are types that are recognized by
    Java and thus safer to use than integers, etc.
  • A final class can be implemented as an enum if
    appropriate within that context
  • An enum that might require specialization is
    better implemented as a class

12
Lexical Elements
  • The source code is a sequence of characters that
    form the lexical elements of the program that is
    stored in a file
  • The compiler (or interpreter) processes those
    characters according to the rules adopted by a
    given language
  • It scans the lexical elements into tokens by
    ignoring whitespace and comments

13
Character Set
  • ASCII and EBCDIC are good for European languages
  • Java is written in a 16 bit encoding of Unicode
  • Unicode defines an encoding format UTF-16 that is
    used in Java to represent text
  • An individual character in a UTF-16 sequence is
    termed a code unit
  • The escape sequence \uxxxx can be used to encode
    a Unicode character
  • Each x in such a sequence is a hexadecimal digit
    (0-9, and a or A-f or F for vales 10-15)

14
Comments
  • Are plain text that help in understanding the
    code
  • They are ignored during scanning
  • Comments can be used to take out code from a
    program
  • // comment single line
  • / comment
  • multiple lines or a part of 1 line
  • /
  • / comment
  • multiple lines
  • /
  • // Object obj new Object()
  • if (false) // never executes
  • Object obj new Object()

15
Tokens
  • The tokens of a language are its basic words
  • Whitespace (spaces, tabs, newlines, form feeds)
    separate tokens
  • Comments are treated as whitespace
  • return 0 // valid statement
  • return0 // error not a statement
  • int j ii // error
  • int j i i // error
  • int j i i // poor
  • int j ii

16
Identifiers
  • Identifiers used for names of variables,
    constants, and methods must start with a letter,
    followed by letters and/or digits
  • int i
  • float fl1
  • method99()
  • enum CAT, DOG4
  • Identifiers can be of any length, and should
    convey the meaning that is understandable within
    a context

17
Keywords
  • Language keywords have special meaning within the
    language
  • They cannot be used as identifiers
  • Java has about 50 keywords
  • null, false, and true are literals not keywords
  • abstract
  • boolean
  • this
  • void
  • int
  • long
  • interface
  • class
  • throws
  • if
  • public

18
Types and Literals
  • Every expression has a type that determines what
    values can be produced
  • The type of an expression is determined by the
    types of values and variables used
  • Types are divided into the primitive types and
    the reference types
  • The primitive types are boolean, char, byte,
    short, int, long, float, double
  • Each primitive type has a class type (i.e.
    wrapper class) defined in the java.lang package
  • The reference types are class, interface, and
    array types
  • Each type has literals, which are the way that
    constant values of that type are written

19
Reference Literals
  • The only literal of object reference is null
  • It can be used anywhere a reference is expected
  • null represents an invalid or uncreated object
  • null has no class
  • null can be assigned to any reference variable

20
Boolean Literals
  • The boolean literals are true and false
  • The wrapper class is called Boolean
  • Boolean defines 2 public static fields that can
    be used
  • Boolean.FALSE is the object corresponding to the
    primitive value false
  • Boolean.TRUE is the object corresponding to the
    primitive value true
  • Boolean.getValue() returns the value of this
    Boolean as a boolean primitive type

21
Character Literals
  • They appear with single quotes (e.g. C)
  • Any valid Unicode character can appear between
    the quotes
  • \uxxxx sequence can be used
  • Octal characters constants
  • can have 3 or fewer digits
  • cannot exceed \377 (\u00ff) (e.g. \12 \n)
  • Special characters represented by an escape
    sequence
  • \n newline (\u000A)
  • \t tab (\u0009)
  • \b backspace (\u0008)
  • \r return (\u000D)
  • \f form feed (\u000C)
  • \\ backslash (\u005C)
  • \ single quote (\u0027)
  • \ double quote (\u0022)
  • \ddd a char by octal value, where each d is one
    of 0-7

22
Integer Literals
  • Integer constants are strings of octal, decimal,
    or hexadecimal digits
  • The start of a constant declares the numbers
    base
  • A 0 starts an octal number (base 8) (e.g. 035)
  • A 0x or 0X starts a hexadecimal number (base 16)
    (e.g. 0x1d or 0X1D)
  • Any other digit (combination) starts a decimal
    number (base 10) (e.g. 29)
  • Integer constants are long if they end in L or l
    (e.g. 29L)

23
Floating-Point Literals
  • Floating-point constants are expressed in either
    decimal or hexadecimal form
  • The decimal form consists of a string of decimal
    digits with an optional decimal point, optionally
    followed by an exponent the letter e or E,
    followed by an optionally signed integer
  • For example 18. 1.8e1 .18E2 180.0e-1
  • The hexadecimal form consists of 0x, a string of
    hexadecimal digits with an optional point,
    followed by a mandatory binary exponent the
    letter p or P, followed by an optionally signed
    integer
  • For example 0x12p0 0x1.2p4 0x.12P8 0x120p-4
  • Floating point constant are of type double unless
    specified with a trailing f or F that makes them
    a float (e.g. 18.0 or 18.0D or 18.0d is a double,
    18.0F is a float)

24
String Literals
  • They appear with double quotes (e.g. a string)
  • To embed a newline use the \n escape sequence
  • To embed a double quote use the \ escape
    sequence
  • A string literal references an object of type
    String

25
Class Literals
  • Every type (primitive or reference) has an
    associated instance of class Class that
    represents that type
  • These instances are often referred as the class
    object for a given type
  • The class object for a type can be named by
    following the type name with .class (e.g.
    String.class, boolean.class)
  • Since Class is generic, the actual type of the
    class literal for a reference type T is ClassltTgt
  • For primitive types it is ClassltWgt, where W is
    the wrapper class for that primitive type (e.g.
    Integer)
  • However, boolean.class and Boolean.class are 2
    different objects of type ClassltBooleangt

26
Variables
  • A variable is a storage location to which a value
    can be assigned
  • A variable can be a field, a local variable in a
    block of code, or a parameter
  • A variable declaration states the identifier
    (name), type, and other attributes of a variable
  • The type part of a declaration specifies what
    kinds of values and behavior are supported by the
    declared entity
  • The other attributes of a variable include
    annotations and modifiers

27
Field and Local Variable Declarations
  • Fields and local variables are declared in the
    same way
  • A declaration is broken into 3 parts
  • modifiers, followed by a
  • type, followed by a list of
  • identifiers
  • Each identifier can have an initializer to give
    it an initial value (e.g. float x 0.2f)
  • Local variables can be declared anywhere within a
    block of code. They can be final but not static
  • Local variables cease to exist when the flow of
    control reaches the end of their block

28
Parameter Variables
  • Are the parameters declared in methods,
    constructors, or catch blocks
  • A parameter declaration consists of an optional
    modifier, a type name, and a single identifier
  • Parameters cannot have explicit initializers
  • Parameter variables cease to exist when the block
    in which they appear completes
  • They can have annotation or be designated as
    final

29
final Variables
  • The final modifier declares that the value of the
    variable is immutable
  • Variables that are final must be initialized
    before being used (e.g. final int id 5 )
  • A blank final is a variable that has not been
    initialized when declared
  • class XX
  • final String name
  • XX (final String name)
  • this.name name
  • final int num
  • num 4
  • num ? 5 // error

30
Array Variables
  • An array provides an ordered collection of
    elements
  • Arrays are objects and extend Object
  • Components of an array can be primitive types or
    references to objects, including references to
    other arrays
  • An array with length 0 is called an empty array
  • int ia new int3
  • the length (i.e. ia.length) of this array is 3
    and cannot be changed, but
  • a new array can be assigned to ia
  • the first element of ia is ia0, the last is
    ia2
  • ia3 or ia-1 throws an ArrayIndexOutOfBoundsExc
    eption
  • for (int i 0i lt ia.lengthi)
  • System.out.println(iai)

31
Array Modifiers
  • An array variable that is declared final means
    that the array reference cannot be changed, not
    the array itself
  • For example
  • final int ia new int3
  • ia0 5
  • ia ? new int5 // error
  • ia0 4

32
Arrays of Arrays
  • A 2 dimensional array is an array of arrays
  • Multidimensional arrays do not necessarily occupy
    a contiguous block of memory
  • The first leftmost dimensions must be specified
  • Other dimensions can be filled later
  • final float mat new float44
  • for (int i 0i lt mat.lengthi)
  • for (int j 0j lt mat.lengthij)
  • System.out.println(matij)
  • float mat new float4
  • mat0 new float3
  • mat1 new float4
  • mat2 new float5
  • mat3 new float6

4
3
4
5
6
33
Array Initialization
  • When an array is created, each element is set to
    the default initial value for its type
  • An array of a reference type stores variables of
    that type
  • String dangers Lions, Tigers
  • String dangers new String(Lions), null
  • String dangers new String Lions,
    Tigers
  • String dangers new String3
  • dangers0 Lions
  • dangers1 null
  • dangers2 ? new Integer(5)
  • String 2darray
  • 1, 2 , 3, 4, 5

34
Array and Types
  • Arrays are implicit extensions of Object
  • This class relationship allows polymorphism for
    arrays
  • An array can be assigned to a variable of type
    Object and cast back
  • Arrays implement the Cloneable interface and the
    Serializable interface
  • Two arrays are equal if they are the same array
  • yArray.equals(yArray) ? true
  • yArray.equals(xArray) ? true
  • yArray.equals(new Y6) ? false
  • An ArrayStoreException is thrown at runtime
    because a Y cannot store references to a X or Z

Object
float
X
X
int
Y
Z
Z
Y
  • Y yArray new Y3
  • X xArray yArray
  • xArray0 new Y()
  • xArray2 ? new X() // error
  • xArray1 ? new Z() // error
  • class ScaleVector extends double
  • // error

35
The Meanings of Names
  • Name management is achieved with 2 mechanisms
  • the namespace is partitioned to give different
    namespaces for different kind of names (e.g.
    multiple methods in different classes can have
    the same name)
  • scoping is used to control the visibility of
    names declared in one part of a program to other
    parts (e.g. use the same local variable name in
    different methods)
  • There are 6 namespaces package names, type
    names, field names, method names, local variable
    and parameter names, and labels
  • Every name declaration has a scope in which it
    can be used (e.g. the scope of a parameter in a
    method is the entire body of that method)
  • Scopes nest an inner scope can access all names
    declared in the outer scope

36
Resolving Names of Variables
  • Each variable must have its type resolved before
    being used. The search order is
  • Local variables declared in the current code
    block, followed by any enclosing code block
  • If the code is in a method or constructor, the
    parameters are searched
  • A field of the class of interface, including any
    accessible inherited fields
  • If the type is a nested type, a variable in the
    enclosing block or field of the enclosing class.
    If the type is a static nested type, only static
    fields of an enclosing type are searched from
    inside out
  • A static field of a class, or interface,
    specifically declared in a static import
    statement
  • A static field of a class, or interface, declared
    in a static import on demand statement

37
Resolving Names of Methods
  • For method names a similar process as for fields
    is followed, but starting at step 3
  • The starting point is in the current class or
    interface
  • The order of searching determines what
    declaration of that method will be found first
    and used

38
Resolving Names of Local Variables
  • The order of searching determines what
    declaration of that variable will be found first
    and used
  • This implies that a name declared in an outer
    scope can be hidden by a name declared in an
    inner scope (e.g. a local variable can hide a
    class field)
  • Hiding is generally bad practice, and is not
    allowed within nested code blocks
  • Blocks that are not nested can reuse the same name
  • int i 0
  • int i 1 // error already defined
  • int i 0
  • int i 1
  • class XX
  • int field
  • void method(int i,int field)
  • int i 0 // error already defined

39
Resolving Names of Types
  • If a name appears in a place where a type name is
    expected then the different type scopes must be
    searched for that name
  • Type scopes are defined by packages and the
    search order is
  • The current type including inherited types
  • A nested type of the current type
  • Explicitly named imported types
  • Other types declared in the same package
  • Implicitly named imported types
  • Hiding of type names is possible, but a type can
    be explicitly referred to by its fully qualified
    name (e.g. java.lang.String)

40
Primitives as Types
  • The separation of primitive types (e.g. byte,
    float) and reference types (i.e. classes and
    interfaces) is a trade-off between efficiency and
    familiarity versus expressiveness and consistency
  • To smooth this separation Java provides a wrapper
    class for each primitive type
  • Automatic conversion between a primitive type and
    its wrapper is enabled
  • boxing primitive-to-reference (e.g. Integer r
    5)
  • unboxing reference-to-primitive (e.g. int i r)

41
The Type Hierarchy
Object
Void
Boolean
Number
Character
Byte
Short
Integer
Double
Float
Long
42
Common Fields and Methods
  • Each wrapper class defines an immutable object
  • Each numeric wrapper defines the following 3
    fields MIN_VALUE, MAX_VALUE, SIZE
  • Some useful methods
  • String toString() a String representation of
    the value
  • boolean equals(Object obj) true if the 2
    objects are the same type and wrap the same value
  • int hashCode() returns a value-based hash code
    for use in hashtables

43
Void
  • The Void class has no value to wrap, provides no
    methods, and cannot be instantiated
  • It only has a static TYPE field containing a
    reference to the Class object void.class
  • There is no void type
  • void is a placeholder indicating no return type,
    i.e. nothing will be returned by the method

44
Number
  • Number is an abstract class extended by all
    wrappers that represent primitive numeric types
  • The abstract methods of Number return the value
    of the object converted to any of the numeric
    types
  • public byte byteValue()
  • public short shortValue()
  • public int intValue()
  • public long longValue()
  • public float floatValue()
  • public double doubleValue()

45
Boxing Conversions
  • A boxing conversion is the automatic conversion
    of a variable of primitive type into an instance
    of its wrapper class
  • Integer r 3
  • int i r ? int i r.intValue()
  • The boxing and unboxing conversions are applied
    automatically
  • A primitive variable cannot be dereferenced
    directly
  • i.toString() // error does not compile
  • ((Object)i).toString() // explicit cast required

46
Boxing in Practice
  • A boxing conversion may need to create an object
    and that is slow and requires memory
  • Given that the wrapper classes are immutable, 2
    objects with the same value can be used
    interchangeably
  • Cached values
  • Type Range
  • boolean true,false
  • byte all values
  • char 0 to 255
  • short -128 to 127
  • int -128 to 127
  • static
  • boolean sameArgs(Integer a,Integer b)
  • return a b
  • sameArgs(3, 3) ? true // automatic, both from
    cache
  • sameArgs(3, new Integer(3)) ? false // one from
    cache, the other is a new
Write a Comment
User Comments (0)
About PowerShow.com