Download presentation
Presentation is loading. Please wait.
1
Enumerations & Annotations
Advanced Programming in Java Enumerations & Annotations Mehdi Einali
2
enum
3
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
4
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; }
5
Bad Implementation2 interface WeekDay{ int Saturday= 1; int Sunday= 2;
int Monday = 3; int Tuesday= 4; } class Client implements WeekDay{ public void foo(){
6
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
7
sample enum Shape { Rectangle, Circle, Square } enum StudentType{
BS, MS, PhD
8
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 }
9
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.
10
Switch on enum
11
More than constant Enum can be a more complex class
With many constructors And fields And methods
13
Implicitly static final
14
Implicit methods
16
annotations
17
Annotation
18
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, …
19
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
20
{"name":"Ali Karimi","number":"7"}
sample {"name":"Ali Karimi","number":"7"}
21
3 different types @Override
22
Write annotation
23
use
24
end
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.