Introduction to Enumerations CMSC 202. Enumerated Values Enumerated values are used to represent a set of named values. Historically in Java (and other.

Slides:



Advertisements
Similar presentations
1 CSE 331 Enumerated types ( enum ) slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia
Advertisements

Java for C++ Programmers Second Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates.
New features in JDK 1.5 Can these new and complex features simplify Java development?
Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view class.
Classes and Objects. What is Design? The parts of the software including – what information each part holds – what things each part can do – how the various.
C How to Program, 6/e © by Pearson Education, Inc. All Rights Reserved.
Intro to CS – Honors I More Objects and Methods GEORGIOS PORTOKALIDIS
Objects, Variables & Methods Java encapsulates data and action modules that access the data in one container, called an object. Object members that.
More methods and classes, 4 of 4 Math 130 Introduction to Programming Lecture # 18 Monday, October 8, 2007.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 7: User-Defined Functions II.
Chapter 7: User-Defined Functions II
Chapter 7: User-Defined Functions II Instructor: Mohammad Mojaddam.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 7 - Pointers Outline 7.1Introduction 7.2Pointer.
Defining classes and methods Recitation – 09/(25,26)/2008 CS 180 Department of Computer Science, Purdue University.
ECE 353: Lab C Pointers and Structs. Basics A pointer holds an address to some variable Notation: – Dereferencing operator: * int *x is a declaration.
Road Map Introduction to object oriented programming. Classes
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 10 - C Structures, Unions, Bit Manipulations,
Lesson 6 - Pointers Outline Introduction Pointer Variable Declarations and Initialization Pointer Operators Calling Functions by Reference Using the const.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 7 - Pointers Outline 7.1Introduction 7.2Pointer Variable Declarations and Initialization 7.3Pointer.
Slides prepared by Rose Williams, Binghamton University Chapter 13 Interfaces and Inner Classes.
Interfaces. In this class, we will cover: What an interface is Why you would use an interface Creating an interface Using an interface Cloning an object.
Introduction to Methods
Chapter 8 Objects & Classes. Definition of Object-Oriented Programming (OOP) Object-Oriented Programming (OOP) uses the analogy of real objects as a template.
CMSC 202 Interfaces. 11/20102 Classes and Methods When a class defines its methods as public, it describes how the class user interacts with the method.
CCSA 221 Programming in C CHAPTER 14 MORE ON DATA TYPES 1 ALHANOUF ALAMR.
The Java Programming Language
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition, Fifth Edition Chapter 7: User-Defined Functions II.
What is an Array? An array is a collection of variables. Arrays have three important properties: –group of related items(for example, temperature for.
C# D1 CSC 298 Elements of C# code (part 2). C# D2 Writing a class (or a struct)  Similarly to Java or C++  Fields: to hold the class data  Methods:
Java Introduction 密碼學與應用 海洋大學資訊工程系 丁培毅.
Constructors CMSC 202. Object Creation Objects are created by using the operator new in statements such as… The following expression invokes a special.
Introduction to Computer Science 2 Slide 1 Enumerated types We already know some data types int, float, char good for problems that involve int,
Java Programming: Program Design Including Data Structures 1 Vectors The class Vector can be used to implement a list Unlike an array, the size of a Vector.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 223 – Advanced Data Structures C++ Review Part-I.
CSSE501 Object-Oriented Development. Chapter 4: Classes and Methods  Chapters 4 and 5 present two sides of OOP: Chapter 4 discusses the static, compile.
1 Generics Chapter 21 Liang, Introduction to Java Programming.
This recitation 1 An interesting point about A3: Using previous methods to avoid work in programming and debugging. How much time did you spend writing.
C Lecture Notes 1 Structures & Unions. C Lecture Notes Introduction Structures –Collections of related variables (aggregates) under one name Can.
Chapter 10 Structures, Unions, Bit Manipulations, and Enumerations Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering.
CIS 270—Application Development II Chapter 8—Classes and Objects: A Deeper Look.
Objects and Classes Continued Engineering 1D04, Teaching Session 10.
Interfaces About Interfaces Interfaces and abstract classes provide more structured way to separate interface from implementation
Recitation 5 Enums and The Java Collections classes/interfaces 1.
1 EPSII 59:006 Spring HW’s and Solutions on WebCT.
Array Size Arrays use static allocation of space. That is, when the array is created, we must specify the size of the array, e.g., int[] grades = new int[100];
StructureStructure. Outline Introduction Structure Definitions Initializing Structures Accessing Members of Structures Using Structures with Functions.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
CS-1030 Dr. Mark L. Hornick 1 References & Pointers.
CPS120 Introduction to Computer Science Exam Review Lecture 18.
Array and Pointers An Introduction Unit Unit Introduction This unit covers the usage of pointers and arrays in C++
Overview of Previous Lesson(s) Over View 3  CLR Programming  Common Language Runtime (CLR) is a programming, that manages the execution of programs,
COMP 14 Introduction to Programming Mr. Joshua Stough March 23, 2005 Monday/Wednesday 11:00-12:15 Peabody Hall 218.
More About Objects and Methods
Chapter 7: User-Defined Functions II
Structure, Unions, typedef and enumeration
Chapter 3: Using Methods, Classes, and Objects
Object-Oriented Programming & Design Lecture 14 Martin van Bommel
Primitive Types Vs. Reference Types, Strings, Enumerations
Object Based Programming
CMSC 202 Interfaces.
We’re slowly working our way towards classes and objects
More About Objects and Methods
CMSC 202 Interfaces.
Chapter 7: User-Defined Functions II
COP 3330 Notes 4/6.
Java Programming Language
CMSC 202 Interfaces.
ITE “A” GROUP 2 ENCAPSULATION.
Presentation transcript:

Introduction to Enumerations CMSC 202

Enumerated Values Enumerated values are used to represent a set of named values. Historically in Java (and other languages), these were often stored as constants. For example, in Java... public static final int SUIT_CLUBS = 0; public static final int SUIT_DIAMONDS = 1; public static final int SUIT_HEARTS = 2; public static final int SUIT_SPADES = 3; 2

Issues with this Approach There are, however, a number of issues with this approach. – Acceptable values are not obvious – No type safety – No name-spacing – Not printable 3

Acceptable Values Not Obvious Since the values are just integers, it’s hard at a glance to tell what the possible values are. Take this method from swing’s JLabel class. Any clue as to what the valid values are for the alignment parameter? – Have to resort to reading the documentation public void setHorizontalAlignment(int alignment) { /*... */ } 4

No Type Safety Since the values are just integers, the compiler will let you substitute any valid integer. For example, there’s nothing stopping one from passing in 1, -3, or into the following method. There’s no way to constrain to only “suit” ints. public void drawSuitOnCard(int suit) { /*... */ } 5

No Name-Spacing With our card example, we prefixed each of the suits with “SUIT_”. We chose to prefix all of those constants with this prefix to potentially disambiguate from other enumerated values of the same class. For example, had we chosen to also enumerate the card faces (e.g. Jack, Queen, …) we would want to make it clear that they were representing the card faces. – For example, we might have “FACE_ACE”. 6

Not Printable Since they are just integers, if we were to print out the values, they’d simply display their numerical value. Similar problem as when reading the method parameters – Need to consult the documents to decipher values 7

Enums to the Rescue Java 5 added an enum type to the language. Declared using the enum keyword instead of class In its simplest form, it contains a comma- separated list of names representing each of the possible options. public enum Suit { CLUBS, DIAMONDS, HEARTS, SPADES } 8

Enums Address These Issues Acceptable values are now obvious — must choose one of the Suit enumerated values… Type safety — possible values are enforced by the compiler 9

Enums Address These Issues Every value is name-spaced off of the enum type itself. Printing the enum value is actually readable. 10 System.out.print("Card is a Queen of " + Suit.HEARTS); // Prints "Card is a Queen of HEARTS"

Additional Benefits Storage of additional information Retrieval of all enumerated values of a type Comparison of enumerated values 11

Storage of Additional Information Enums are objects So they can have… – Member variables – Methods For example… – We could embed the color of the suit within the Suit. – We can then read the value using a getter, etc. 12 public enum Suit { CLUBS(Color.BLACK), DIAMONDS(Color.RED), HEARTS(Color.RED), SPADES(Color.BLACK); private Color color; // Java will prevent construction // outside of enum declaration Suit(Color c) { this.color = c; } public Color getColor() { return this.color; }

Retrieval of All Enumerated Values All enum types will automatically have a values() method that returns an array of all enumerated values for that type. 13 Suit[ ] suits = Suit.values(); for(Suit s : suits) { System.out.println(s); }

Comparison of Enumerated Values Since users cannot construct enum instances, there can only be one instance of each value. As such, we can actually compare enums using the == operator. 14 if(suit == Suit.CLUBS) { // do something }

Comparison of Enumerated Values Enums can also be used with the switch control structure. 15 Suit suit = /*... */; switch (suit) { case CLUBS: case SPADES: // do something break; case HEARTS: case DIAMONDS: // do something else break; default: // yet another thing break; }

One Gotcha If you have a reference to an enum instance, then you’re assured to have a valid value. The key word being “if” — you’ll likely still need to check that the reference is set. – In other words, you may need to check that the reference does/doesn’t refer to null. 16