Professional Documents
Culture Documents
Enumerations: CS F213: Object Oriented Programming
Enumerations: CS F213: Object Oriented Programming
Dipanjan Chakraborty
Department of CS&IS
1
What are Enumerations
●
A list of named constants that define a new data type and its legal
values
●
An enumeration object can hold only a value that was declared in
the list
–
Other values are not allowed
●
In Java, an enumeration defines a class type
–
In Java, an enumeration can have constructors, methods, and
instance variables, can implement interfaces
–
However, an enumeration can not inherit another class or be
extended by another class
2
Enumeration example
1 enum BITSPilani {
2 Dubai, Hyderabad, Goa, Pilani
3 }
●
The identifiers Dubai, Hyderabad, etc. are called
enumeration constants
– Implicitly declared as a public, static final
member of BITSPilani
●
Their type is BITSPilani
●
These constants are called self-typed 3
Enumeration example
1 BITSPilani bp;
2 bp = BITSPilani.Hyderabad;
3
4 if (bp == BITSPilani.Goa) //false
5
6 switch(bp) {
7 case Hyderabad:
8 //DoSomething;
9 break;
10 case Goa:
11 //DoSomething;
12 break;
13 ...
14 }
4
Values() and valueOf() methods
●
The values() method returns an array that
contains a list of the enumeration constants
●
valueOf(String str) returns the enumeration
constant whose value corresponds to the
string passed in str
5
Values() and valueOf() methods
1 for (BITSPilani bp : BITSPilani.values())
2 System.out.println(bp);
1 bp = BITSPilani.valueOf(“Pilani”); // Pilani
6
Enumerations are Class Types
●
Each enumeration constant is an object of its enumeration
type
●
The constructor is called when each enumeration constant is
created
●
Each enumeration constant has its own copy of any instance
variables defined by the enumeration
●
Constructors can be overloaded
●
Let’s see an example
7
Enumerations are Class Types
●
All enums inherit java.lang.Enum class by default (an exception as enums can
not inherit classes)
●
Built-in methods:
– final int ordinal(): returns the ordinal value of the invoking constant.
Values start at 0
– final int compareTo(enum-type e): If the invoking constant has an
ordinal value less than e’s, then compareTo( ) returns a negative value. If
the two ordinal values are the same, then zero is returned. If the invoking
constant has an ordinal value greater than e’s, then a positive value is
returned.
8
Autoboxing
Dipanjan Chakraborty
Department of CS&IS
9
Type Wrappers
●
Java uses primitive data types for efficiency
– These do not inherit the Object class
●
However, object representations of primitive data
types are required at times:
– Primitive data types can not be passed by
reference
– Some Java data structures only operate on objects
10
Type Wrappers
●
Double, Float, Long, Integer, Short, Byte,
Character, Boolean
●
Constructors are deprecated for memory
efficiency
●
Instead the static valueOf() method may be used
– static Character valueOf(char ch)
11
Numeric Type Wrappers
●
Double, Float, Long, Integer, Short, Byte
– Inherit the abstract class Number
●
Number declares the following methods, these are implemented by the Numeric Type
Wrappers:
– byte byteValue( )
– double doubleValue( )
– float floatValue( )
– int intValue( )
– long longValue( )
– short shortValue( )
12
Numeric Type Wrappers
●
Examples:
– static Integer valueOf(int val)
– static Integer valueOf(String valStr)
throws NumberFormatException
– Integer iOb = Integer.valueOf(“OOP”);
13
Autoboxing
●
Modern versions of Java have included two important
features: autoboxing and auto-unboxing
●
Autoboxing is the process by which a primitive type is
automatically encapsulated (boxed) into its equivalent
type wrapper whenever an object of that type is
needed. There is no need to explicitly construct an
object
●
Integer iOb = 100;
14
Auto-unboxing
●
Auto-unboxing is the process by which the value
of a boxed object is automatically extracted
(unboxed) from a type wrapper when its valueis
needed
●
There is no need to call a method such as
intValue( ) or doubleValue( )
●
int i = iOb;
15
In methods and expressions
1 static int m(Integer v) { 1 public static void main(String[] args) {
2 return v; 2 Integer iOb = m(100);
3 } 3 System.out.println(iOb);
4 }
●
Similar behaviour for Characters and Booleans
16
Overhead
●
Autoboxing and Auto-unboxing adds an
overhead
●
They should be used only when an object
representation of a primitive type is required
●
For all other cases stick to the primitive type
for efficiency
17
Annotations
Dipanjan Chakraborty
Department of CS&IS
18
Annotations
●
Java’s way of embedding supplemental
information into a source file
●
Does not change the actions of the program:
leaves the semantics of a program unchanged
19
Annotations
●
Information for the compiler — Annotations can be
used by the compiler to detect errors or suppress
warnings.
●
Compile-time and deployment-time processing —
Software tools can process annotation information to
generate code, XML files, and so forth.
●
Runtime processing — Some annotations are available
to be examined at runtime.
20
Annotations
1 @interface MyAnno { ●
Annotations are based on interface
2 String str();
3 int val(); ●
The @ sign indicates an annotation type being declared
4 } ●
All annotations comprise solely method declarations,
no bodies
●
Annotation can not include the extends clause
1 @MyAnno(str = "Annotation
– All annotations automatically extend
Example", val = 100)
2 public static void myMeth() { // ... java.lang.annotation package
●
Any declaration can have an annotation associated
– classes, methods, fields, parameters, and enum
constants can be annotated
– The annotation fields must be given values (like
data members)
21
Annotations: Retention Policy
●
SOURCE: is retained only in the source file and is
discarded during compilation
●
CLASS: is stored in the .class file during compilation.
However, it is not available through the JVM during run
time
●
RUNTIME: is stored in the .class file during compilation
and is available through the JVM during run time
– offers the greatest annotation persistence
22
Annotations: Retention Policy
@Retention(RetentionPolicy.RUNTIME)
1 @interface MyAnno {
2 String str();
3 int val();
4 }
●
Default policy is CLASS
23
Obtaining Annotations at Run Time
●
reflection can be used to obtain the annotations
– java.lang.reflect package
●
Obtain the class (getClass())
●
Obtain the (getMethod(String methodName)
●
Obtain the annotations (getAnnotation(Class<A> annotationType)
●
To obtain all annotations that have runtime retention associated
with an item:
– getAnnotations()
24
Annotations: Retention Policy
1 class Meta {
2 @MyAnno(str = "Annotation Example", val = 100)
3 public static void myMeth() {
4 Meta ob = new Meta();
5 try {
6 Class<?> c = ob.getClass(); // Generics
7 Method m = c.getMethod("myMeth");
8 MyAnno anno = m.getAnnotation(MyAnno.class);
9 System.out.println(anno.str() + " " + anno.val());
10 } catch (NoSuchMethodException exc) {
11 System.out.println("Method Not Found.");
12 }
13 }
25
AnnotedElement interface
●
Annotation[] getDeclaredAnnotations()
– Returns all non-inherited annotations present
in the invoking object
●
default boolean isAnnotationPresent(Class<?
extends Annotation> annotationType)
– Returns true if annotation annotationType is
associated with the invoking object
26
Annotations: Default Values
1 @interface MyAnno {
2 String str() default "Testing";
3 int val() default 100;
4 }
27
Marker Annotations
●
An annotation with no members
– Used to mark an item
●
Can be determined with isAnnotationPresent()
method
28
Single-Member Annotations
●
Only one member present
●
Value can be directly specified without the
name of the member
– @MyAnnotation(100)
29
Built-in Annotations
●
@Retention (described earlier)
●
@Documented: marker annotation for another annotation
indicating that an annotation needs to be documented
●
@Target: specifies the types of items to which an annotation can
be applied. It is meant to be an annotation for another
annotation
– e.g. @Target( { ElementType.CONSTRUCTOR,
ElementType.LOCAL_VARIABLE } )
30
Built-in Annotations
●
@Inherited: marker annotation to be used on class declarations
–
Causes the annotation of a superclass to be inherited by a
subclass
●
@Override: marker annotation for methods. A method
annotated with @Override must override a method from a
superclass. If it doesn’t, a compile-time error will result. It is
used to ensure that a superclass method is actually overridden,
and not simply overloaded.
●
@Deprecated: indicates that a declaration is obsolete and not
recommended for use
31
Built-in Annotations
●
@FunctionalInterface: marker annotation for interfaces
– Indicates that an interface contains only one abstract method
●
@SafeVarargs: marker annotation that can be applied to methods and
constructors
– indicates that no unsafe actions related to a varargs parameter
occur.
●
@SuppressWarnings: specifies that one or more warnings that might
be issued by the compiler are to be suppressed
– The warnings to suppress are specified by name, in string form.
32
Type Annotations
●
Modern versions of Java allow annotations to be specified in
most cases in which a type is used
– e.g. the return type of a method, the type of this within a
method, a cast, array levels, an inherited class, a throws
clause, generic types
●
A type annotation must include ElementType.TYPE_USE as a
target
●
Refer to example in the textbook
33
Repeating Annotations
●
A repeatable annotation must be annotated with
@Repeatable annotation
34
Restrictions
●
No annotation can inherit another
●
All methods declared by an annotation must be without parameters.
●
They must return one of the following:
– A primitive type, such as int or double
– An object of type String or Class
– An object of an enum type
– An object of another annotation type
– An array of a legal type.
●
Annotations cannot be generic (Generics will be covered later)
●
Annotation methods cannot specify a throws clause.
35
How are Annotations Used?
●
It is possible to write Annotation Processors
●
These may take a Java source code (or byte code) and generate
Java source code
●
Used during compile time
●
Read more here:
–
http://hannesdorfmann.com/annotation-processing/
annotationprocessing101/
–
https://deors.wordpress.com/2011/10/08/annotation-processors/
–
https://www.oracle.com/technical-resources/articles/hunter-met
a2.html
–
e.g. https://checkerframework.org/ 36