Enumerations & Annotations Advanced Programming in Java Enumerations & Annotations Mehdi Einali
enum
Enumerations Suppose you have a type with a few instances Example: Student Type : <BS, MS, PhD> SMS Status : <Sent, Delivered, Not Delivered, Not Sent> WeekDay: <Saturday, Sunday, Monday, …> How do you implement it? The class should not be inherited The instances are limited: no further instances
Bad Implementation1 final class WeekDay{ public static final WeekDay Saturday= new WeekDay(1); public static final WeekDay Sunday= new WeekDay(2); public static final WeekDay Monday = new WeekDay(3); public static final WeekDay Tuesday= new WeekDay(4); private int code; private Color(int i) { this.code = i; }
Bad Implementation2 interface WeekDay{ int Saturday= 1; int Sunday= 2; int Monday = 3; int Tuesday= 4; } class Client implements WeekDay{ public void foo(){
Java enum Java introduces enumerations for this purpose Enumerated Data Type A simple class enum keyword instead of class or interface Comma seperated enum instances enum instances are constant
sample enum Shape { Rectangle, Circle, Square } enum StudentType{ BS, MS, PhD
use Color color = Color.Black; Shape shape = Shape.Circle; show(shape, color); ... private static void show ( Shape shape, Color color) { //show a shape with this color }
Enum Characteristics enum types are implicitly final Can not be a super-class Because they declare constants that should not be modified Instances are constants enum constants are implicitly public, static and final No new instances can be created object instantiation of enum types with operator new results in a compilation error.
Switch on enum
More than constant Enum can be a more complex class With many constructors And fields And methods
Implicitly static final
Implicit methods
annotations
Annotation
What is annotation An annotation is a special form of metadata Added to Java source code Classes, methods, variables, parameters and packages may be annotated Unlike Javadoc tags, Java annotations can be reflective They can be embedded in class files (byte code) May be retained by the Java VM at run-time Example @Override, @Deprecated, @ SuppressWarnings, …
Why Annotation? Enables “declarative programming” style Less coding since tool will generate the boliler plate code from annotations in the source code Easier to change Eliminates the need for maintaining "side files" that must be kept up to date with changes in source files Information is kept in the source file example) Eliminate the need of deployment descriptor
{"name":"Ali Karimi","number":"7"} sample {"name":"Ali Karimi","number":"7"}
3 different types @Override
Write annotation
use
end