Type Safety and Enumerations. Type Checking and Type Errors  The type system defines data types and the operations on data types.  A type error occurs.

Slides:



Advertisements
Similar presentations
Java for C++ Programmers Second Night. Overview First Night –Basics –Classes and Objects Second Night –Enumerations –Exceptions –Input/Output –Templates.
Advertisements

Exceptions Session 21. Memory Upload Creating Exceptions Using exceptions to control object creation and validation.
Problem Solving 5 Using Java API for Searching and Sorting Applications ICS-201 Introduction to Computing II Semester 071.
METHOD OVERRIDING Sub class can override the methods defined by the super class. Overridden Methods in the sub classes should have same name, same signature.
Singleton vs utility class  at first glance, the singleton pattern does not seem to offer any advantages to using a utility class  i.e., a utility class.
Composition CMSC 202. Code Reuse Effective software development relies on reusing existing code. Code reuse must be more than just copying code and changing.
1-May-15 Java 1.5. Reason for changes “The new language features all have one thing in common: they take some common idiom and provide linguistic support.
Introduction to Programming Lecture 34. In Today’s Lecture Arrays of objects Arrays of objects Interaction of Arrays with Free Store Interaction of Arrays.
Java Exceptions. Types of exceptions  Checked exceptions: A checked exception is an exception that is typically a user error or a problem that cannot.
Enumerated data type & typedef. Enumerated Data Type An enumeration consists of a set of named integer constants. An enumeration type declaration gives.
Nov 10, Fall 2006IAT 8001 Debugging. Nov 10, Fall 2006IAT 8002 How do I know my program is broken?  Compiler Errors –easy to fix!  Runtime Exceptions.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
C#.NET C# language. C# A modern, general-purpose object-oriented language Part of the.NET family of languages ECMA standard Based on C and C++
1 Chapter 2 Introductory Programs. 2 Getting started To create and run a Java program –Create a text file with a.java extension for the source code. For.
STREAM STREAM A software process The Mañana Principle The Mañana Principle Don’t try to everything at once! Static Methods Static Methods Stateless Utility.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 10 - Structures, Unions, Bit Manipulations, and Enumerations Outline 10.1Introduction 10.2Structure.
CSc2310 tutoring session, week 8 Fall, 2012 Haidong Xue 5:30pm—8:30pm 10/30/2012 and 10/31/2012 -Code PrintCalendar.
1 Chapter 10 Various Topics User defined Types Enumerated Types Type Casting Syntactic Sugar Type Coercion.
Session 5 java.lang package Using array java.io package: StringTokenizer, ArrayList, Vector Using Generic.
Jun 16, 2014IAT 2651 Debugging. Dialectical Materialism  Dialectical materialism is a strand of Marxism, synthesizing Hegel's dialectics, which proposes.
1 JavaScript. 2 What’s wrong with JavaScript? A very powerful language, yet –Often hated –Browser inconsistencies –Misunderstood –Developers find it painful.
CCSA 221 Programming in C CHAPTER 14 MORE ON DATA TYPES 1 ALHANOUF ALAMR.
Java Implementation: Part 3 Software Construction Lecture 8.
The Java Programming Language
CECS 220 Java Test Review. Variable Names 0 May Contain: a-z, A-Z, 0-9, _, $, characters from other languages. 0 May not start with Legal: 0 MyVariable.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
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:
1 Scope Scope describes the region where an identifier is known, and semantic rules for this.
CSE 425: Data Types I Data and Data Types Data may be more abstract than their representation –E.g., integer (unbounded) vs. 64-bit int (bounded) A language.
Java 5 Part 1 CSE301 University of Sunderland Harry Erwin, PhD.
Pointers and Dynamic Memory Allocation Copyright Kip Irvine 2003, all rights reserved. Revised 10/28/2003.
CSC1401 Classes - 2. Learning Goals Computing concepts Adding a method To show the pictures in the slide show Creating accessors and modifiers That protect.
Programming in Java CSCI-2220 Object Oriented Programming.
Session 7 Methods Strings Constructors this Inheritance.
Midterm 2 Review 1. 2 Object Oriented Programming Write a Date class. It should contain fields for day, month, year, number of months per year, and number.
C# C1 CSC 298 Elements of C# code (part 1). C# C2 Style for identifiers  Identifier: class, method, property (defined shortly) or variable names  class,
Objects & Classes Weiss ch. 3. So far: –Point (see java.awt.Point) –String –Arrays of various kinds –IPAddress (see java.net.InetAddress) The Java API.
Working With Objects Tonga Institute of Higher Education.
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.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
CreatingClasses-SlideShow-part31 Creating Classes part 3 Barb Ericson Georgia Institute of Technology Dec 2009.
Puzzle 1  what does the following program print? public class Puzzle01 { public static void main(String[] args) { System.out.print("C" + "S" + "E"); System.out.println('1'
CMSC 202 Advanced Section Classes and Objects: Object Creation and Constructors.
1 EPSII 59:006 Spring HW’s and Solutions on WebCT.
CMSC 202 Java Classes and Object 2nd Lecture. Aug 6, Stack and Heap When your program is running, some memory is used to store local variables.
How to execute Program structure Variables name, keywords, binding, scope, lifetime Data types – type system – primitives, strings, arrays, hashes – pointers/references.
Spring 2009 Programming Fundamentals I Java Programming XuanTung Hoang Lecture No. 8.
Introduction To Objects Oriented Programming Instructor: Mohammed Faisal.
CIS162AD Constructors Part 2 08_constructors.ppt.
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
Object Oriented Programming Lecture 2: BallWorld.
Today Encapsulation. Build a fully encapsulated Halloween class, going from Halloween1 to Halloween6 (eventually!): –The final version will have overloaded.
Dr. M. Al-Mulhem Introduction 1 Chapter 6 Type Systems.
Heath Carroll Bill Hanczaryk Rich Porter.  A Theory of Type Polymorphism in Programming ◦ Robin Milner (1977)  Milner credited with introducing the.
OOP Tirgul 12.
Computer Organization and Design Pointers, Arrays and Strings in C
Classes and Objects 2nd Lecture
Classes and Objects: Encapsulation
Classes and Objects Encapsulation
(and a review of switch statements)
(and a review of switch statements)
Lecture 15 (Notes by P. N. Hilfinger and R. Bodik)
Java Classes and Objects 3rd Lecture
An "enum" is a type with a fixed set of elements.
CMSC 202 Interfaces.
Subtype Substitution Principle
CMSC 202 Encapsulation Version 9/10.
Classes and Objects Object Creation
CMSC 202 Constructors Version 9/10.
Presentation transcript:

Type Safety and Enumerations

Type Checking and Type Errors  The type system defines data types and the operations on data types.  A type error occurs if an operation is performed on a value where the operation isn't defined or not well- defined. char c; scanf("%f", &c); /* error: double => char */  The translator (compiler, interpreter) seeks to avoid type errors by type checking. Type checking can be done statically or dynamically.  Languages like Java also catch type errors at run-time and raise ("throw") exceptions.

Run-time Type Checking Student s = new Student("joe"); Object o = s.clone(); JFrame t = (JFrame) o; throws a ClassCastException

Type Safety (1)  A program is considered "type safe" if it can be verified that it is free of type errors.  In strongly typed languages like Java, this would seem like an easy task... but its not!  Is the java.util.ArrayList class type safe?

Type Safety (2)  Is the java.util.ArrayList class type safe? java.util.Arrays static void sort( Object [ ] array ); import java.awt.Color;... Object [ ] a = { new Double(0.5), Color.RED, "hello" }; java.util.Arrays.sort( a ); // run-time ClassCastException ! from the Java 2 SDK API

Type Safety (2)  Arrays.sort throws a ClassCastException.  Programmer isn't required to catch RuntimeExceptions, so this will compile OK but fail at run-time. Another example:  Is the java.util.Date class type safe? java.util.Date public Date(int year, int month, int day); // Date(year-1900, month /* jan=0, feb=1 */, dom ) int year = 2000; int month = 0; // jan = 0, feb = 1, mar = 2,... int day = 1; // day of month Date newyear = new Date( year , month, day ); from the Java 2 SDK API

Type Safety (3)  But, its sooo easy to forget... Date( year, month, day ) ??? Date( day, month, year ) ??? Date( month, day, year ) ??? int year = , month = 0, day = 1; Date d1 = new Date( year, month, day ); Date d2 = new Date( day, month, year ); Date d3 = new Date( month, day, year ); d1.toString() --> "Sat Jan 01 00:00:00 ICT 2000" d2.toString() --> "Wed Apr 10 00:00:00 ICT 1901" d3.toString() --> "Fri May 11 00:00:00 ICT 1900" more coffee, please

Type Safety (4)  Calendar class has static constants for the months, but the values are same as "int". Calendar.JANUARY = 1 Calendar.FEBRUARY = 2  They doesn't help type checking or type safety. int year = , month = 0, day = 1; Date d1 = new Date( year, Calendar.JANUARY, day ); Date d2 = new Date( day, Calendar.JANUARY, year ); Date d3 = new Date( Calendar.JANUARY, day, year ); Its your fault!!!! You should have been more careful.

Enumerations: promoting type safety  Enumerated types were introduced in Pascal. type months = ( jan, feb, mar, apr,..., dec ); procedure date(Year: int; Month: months; Day: int) begin... end; (* main method *) var thismonth : months; (* variable of months type *) begin thismonth := jan; date(2000, thismonth, 1); compiler can verify argument is valid. No brainer!

Java Enumerations: enum  "enum" is like a class when static instances of itself. public enum Month { /* the allowed values of this type: */ JANUARY, FEBRUARY, MARCH, APRIL,... DECEMBER; } public class MyDate { int year = 2005; Month month = Month.DECEMBER; int day = 9; The values of this enumeration

enum can have attributes, too  set the attributes in a constructor: public enum Month { /* the allowed values of this type: */ JANUARY("January",0), FEBRUARY("February",1), MARCH("March",2),... DECEMBER; /* attributes */ public final String name; private int index; /* the constructor */ Month( String name, String index) { this.name = name; this.index = index; }

enum members are printable  If an enum has a toString( ) method, it is used.  If an enum doesn't have toString( ), the enum member name is printed! System.out.println( Month.JANUARY ); System.out.println( Month.JANUARY.name ); Output: JANUARY January

A Safer Date Class public class MyDate { /* attributes */ private int year; private Month month; private int day; /* the constructor */ public MyDate( int year, Month month, int day) { this.year = year; this.month = month; this.day = day; } public String toString() { return ""+day+" "+month.name+" "+year; }

MyDate  MyDate requires that the 2nd argument be a month: programmer can put in an invalid value. MyDate my = new Date(2005, Month.MAY, 1);  Use the ".name" property to print month as string. MyDate d1 = new MyDate( 2005, Month.DECEMBER, 9 ); MyDate d2 = new MyDate( 2005, 12, 9 ); // Error System.out.println( "Today is " + d1); Today is 9 December 2005

enum values() method  Java automatically supplies a method named values () that returns an array of all values in the enumeration. For the Month enum : Month [ ] mlist = Month.values( ); for( Month m : Month.values() ) // loop for all values System.out.println( m ); JANUARY FEBRUARY MARCH APRIL MAY JUNE...

enum for Token Types public enum TokenType { /* the allowed values of this type: */ IDENT( "[A-Za-z_]\\w*" ), NUMBER( "(\\d+\\.?|\\.\\d)\\d*([Ee][+-]?\\d+)?" ), OPERATOR( "[-+*/^]" ), ASSIGN( "=" ), SEPARATOR( "[()]" ); /* attributes */ public final String regex; public final Pattern pattern; /* constructor */ Tokens( String regex ) { this.regex = regex; this.pattern = Pattern.compile(regex); }  Good OO design: object contains its own properties

Using Token Types public class Token { /* token has a type and value */ private TokenType type; private String value; Token(TokenType type, Double value) { this.type = type; this.value = value; } /* return the token type */ TokenType type() { return type; } }  enum members are unique. You can use '==' to test if ( token.type() == TokenType.IDENT )... if ( token.type() == TokenType.NUMBER )...

Advantages of using Enumeration 1. Type safety. 2. Collect all properties of a token in a single place (token name, token regular expression,...) 3. More efficient than using String for testing. 4. Avoid mistyping of String name in comparison. Compare: if ( token.type.equals("NUMBER") )... if ( token.type.equals("IDENT") )... If you use the wrong string value then the error is not detected, but the code won't work. if ( token.type == Token.NUMBER )... if ( token.type == Token.IDENT )...

How to Hide the enum  To minimize changes in your program, you can try... public class Token { public static TokenType IDENT = TokenType.IDENT; public static TokenType NUMBER = TokenType.NUMBER;... /* can make "type" attribute immutable public */ public final TokenType type;... } if ( token.type == Token.IDENT )... if ( token type == Token.NUMBER )... same as TokenType.NUMBER

Compare all token types  In your tokenizer class, you can use values(): public class Tokenizer { String s; TokenType type = null;... /* can make "type" attribute immutable public */ for ( TokenType t : TokenType.values() ) if ( s.matches( t.regex ) ) type = t; token = new Token( s, type );