OOP Tirgul 12.

Slides:



Advertisements
Similar presentations
COSC 2006 Data Structures I Instructor: S. Xu URL:
Advertisements

Written by: Dr. JJ Shepherd
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Road Map Introduction to object oriented programming. Classes
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
Fall 2007CS 2251 Enum Types from Java Software Solutions Foundations of Program Design Sixth Edition by Lewis & Loftus.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
Fundamental Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
Options for User Input Options for getting information from the user –Write event-driven code Con: requires a significant amount of new code to set-up.
Principles of Computer Programming (using Java) Review Haidong Xue Summer 2011, at GSU.
Comp 248 Introduction to Programming Chapter 4 - Defining Classes Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
The Java Programming Language
Basic Java Programming CSCI 392 Week Two. Stuff that is the same as C++ for loops and while loops for (int i=0; i
Java Quiz Bowl A fun review of the Java you should know from CMPT 201 If you don’t know the answers - this week is for you to study up!
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.
Chapter 2: Java Fundamentals
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
Methods in Java. Program Modules in Java  Java programs are written by combining new methods and classes with predefined methods in the Java Application.
Java development environment and Review of Java. Eclipse TM Intergrated Development Environment (IDE) Running Eclipse: Warning: Never check the “Use this.
Programming in Java CSCI-2220 Object Oriented Programming.
1 Enumerations and Structs Chapter 9. 2 Objectives You will be able to: Write programs that define and use enumeration variables. Write programs that.
ISBN Chapter 6 Data Types Introduction Primitive Data Types User-Defined Ordinal Types.
BEGINNING PROGRAMMING.  Literally – giving instructions to a computer so that it does what you want  Practically – using a programming language (such.
COP3502 Programming Fundamentals for CIS Majors 1 Instructor: Parisa Rashidi.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
08 Encapsulation and Abstraction. 2 Contents Defining Abstraction Levels of Abstraction Class as Abstraction Defining a Java Class Instantiating a Class.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
User Defined Methods Methods are used to divide complicated programs into manageable pieces. There are predefined methods (methods that are already provided.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Programmeren 1 6 september 2010 HOORCOLLEGE 2: INTERACTIE EN CONDITIES PROGRAMMEREN 1 6 SEPTEMBER 2009 Software Systems - Programming - Week.
Spring 2009 Programming Fundamentals I Java Programming XuanTung Hoang Lecture No. 8.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
Structured Programming Dr. Atif Alhejali Lecture 4 Modifiers Parameters passing 1Structured Programming.
CSE 501N Fall ‘09 03: Class Members 03 September 2009 Nick Leidenfrost.
1 Lecture # 2. * Introducing Programming with an Example * Identifiers, Variables, and Constants * Primitive Data Types * Byte, short, int, long, float,
Programming in Java Transitioning from Alice. Becomes not myFirstMethod but …. public static void main (String[] arg) { // code for testing classes goes.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
Chapter VII: Arrays.
Modern Programming Tools And Techniques-I
JAVA MULTIPLE CHOICE QUESTION.
Chapter 7 User-Defined Methods.
3 Introduction to Classes and Objects.
Java Primer 1: Types, Classes and Operators
Lecture 2: Data Types, Variables, Operators, and Expressions
Chapter 3: Using Methods, Classes, and Objects
University of Central Florida COP 3330 Object Oriented Programming
Generics, Lambdas, Reflections
Control Statement Examples
Subroutines Idea: useful code can be saved and re-used, with different data values Example: Our function to find the largest element of an array might.
Chapter 9 Inheritance and Polymorphism
Java Programming Language
Conditional Statements
Introduction to Java Programming
(and a review of switch statements)
(and a review of switch statements)
Chapter 1: Computer Systems
More On Enumeration Types
Anatomy of a Java Program
Generics, Lambdas, Reflections
CMPE212 – Reminders Assignment 3 due next Friday.
Fundamental OOP Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
Class.
In this class, we will cover:
Java 5 New Features 1-May-19.
Chap 2. Identifiers, Keywords, and Types
Chapter 7 Objects and Classes
Presentation transcript:

OOP Tirgul 12

What will we be seeing today? Enums Ex6 CLIDS Lecture 11 @ cs huji 2013

Enums

Enums Motivation An enum type is a special data , used to define a set of predefined constants. A variable of an enum type can only be assigned with a constant from the set defined for that enum type.  Naming convention  CLIDS Lecture 11 @ cs huji 2013

What is the problem with this representation? Enums Motivation Say you want to write a program that requires a representation of the seasons of the year: לשאול בע"פ, שקף הבא תשובות. What is the problem with this representation? CLIDS Lecture 11 @ cs huji 2013

Enums Motivation Not typesafe – season is just an int You can pass any int value to chooseShirt() What is WINTER + 3? Hard to update – what if you want to add a new season between spring and summer (say, END_OF_SPRING)? Need to change values of other members Uninformative printing System.out.println(SUMMER) prints 2 לשים דגש על type-safety CLIDS Lecture 11 @ cs huji 2013

Enums Solution Use Enums! final CLIDS Lecture 11 @ cs huji 2013

Without Enums Not typesafe With Enums Compilation Error בלי enums – אין type-safety chooseShirt(1223); chooseShirt(122); chooseShirt(“SUMMER”); chooseShirt(Season.SUMMER); CLIDS Lecture 11 @ cs huji 2013

Without Enums Not typesafe בלי enums – אין type-safety Compilation Error CLIDS Lecture 11 @ cs huji 2013

Enums Properties Enums are actually java classes Denoted enum type (implicitly extends java.lang.enum) Season.values() – Iterate over enum values Can have members and methods Constructor must have either package or private access:  Declaring an enum constructor as public or protected will produce a compile-time error. The default constructor access modifier is private You cannot invoke an enum constructor yourself. Enum has its own namespace (Color.BLUE, Season.SUMMER,…). Cannot add/change values in runtime ≥ Java 5 http://stackoverflow.com/questions/7747948/why-can-a-enum-have-a-package-private-constructor It is a compile-time error if the constructor of an enum type (§8.9) is declared public or protected. If no access modifier is specified for the constructor of an enum type, the constructor is private הכוונה היא שגם כשלא כתוב private, הבנאי הוא פרטי CLIDS Lecture 11 @ cs huji 2013

Enums Complex Example Used during construction Constructor (declared either private or package) CLIDS Lecture 11 @ cs huji 2013

Enums Complex Example Output: CLIDS Lecture 11 @ cs huji 2013

Enums example II public enum Operation { PLUS, MINUS, TIMES, DIVIDE; // Do arithmetic op’ represented by this constant double eval(double x, double y){ switch(this) { case PLUS: return x + y; case MINUS: return x - y; case TIMES: return x * y; case DIVIDE: return x / y; } throw new UnsupportedOperationException("Unknown op: "+this); If we add a new option and not add it in eval(), we might get an exception

String to Enum public class Calculator { public static void main(String[] args) { String input = args[0]; Operation o = Operation.valueOf(input); System.out.println(o.eval(Integer.parseInt(args[1]), Integer.parseInt(args[2]))); } args[0] args[1] args[2] Operation Number 1 Number 2

Enums example II We can define an abstract method which has to be implemented by each type public enum Operation { PLUS { double eval(double x, double y) { return x + y; } }, MINUS { double eval(double x, double y) { return x - y; } }, TIMES { double eval(double x, double y) { return x * y; } }, DIVIDE { double eval(double x, double y) { return x / y; } }; // Do arithmetic op represented by this constant abstract double eval(double x, double y); }

Enums When to use? If you need a fixed set of constants Pros: The planets, days of the week, seasons… Other sets where you know all possible values at compile time Choices on a menu, command line flags, etc’ Pros: Type safety Understandability valueOf method makes it easy to convert from strings to enum values CLIDS Lecture 11 @ cs huji 2013

Enums When not to use? If your objects are not known in advance (at compile time) An Enum defines an object-pool. Each object is instantiated when it is first used. Therefore Enums should never be used as value objects or have attributes that get set during usage CLIDS Lecture 11 @ cs huji 2013

ordinal() Returns the ordinal of this enumeration constant (its position in its enum declaration)  the first constant is assigned an ordinal of zero Most programmers will have no use for this method. It is designed for use by sophisticated enum-based data structures (where the keys are Enums): EnumSet EnumMap They use enums as keys

Ex6

Ex 6 Building a verifier for s-java Legal code Illegal code להגיד שזה לא קומפיילר אמיתי ושהמטרה להגיד אם התקמפל או לא ולא לייצר קוד בינארי System.out.println(0) System.out.println(1) CLIDS Lecture 11 @ cs huji 2013

Ex6 – running the testers CLIDS Lecture 11 @ cs huji 2013

Ex6 – running the testers CLIDS Lecture 11 @ cs huji 2013

Ex6 – running the testers CLIDS Lecture 11 @ cs huji 2013

Ex6 S-java supports: Comments (of a single line) Variables Methods CLIDS Lecture 11 @ cs huji 2013

Ex6 - Comments One line comment CLIDS Lecture 11 @ cs huji 2013

type name = value; Ex6 - Variables Defining primitive variables: CLIDS Lecture 11 @ cs huji 2013

type name = value; Ex6 - Variables Defining primitive variables: int double boolean String char CLIDS Lecture 11 @ cs huji 2013

type name = value; Ex6 - Variables Defining primitive variables: foo CLIDS Lecture 11 @ cs huji 2013

type name = value; Ex6 - Variables Defining primitive variables: agrees with the type לדבר על זה שdouble הוא גם int CLIDS Lecture 11 @ cs huji 2013

type name = value; Ex6 - Variables Defining primitive variables: agrees with the type Can be: a number Existing initialized variable CLIDS Lecture 11 @ cs huji 2013

type name = value; Ex6 - Variables Defining primitive variables: agrees with the type Can be: a number Existing initialized variable int a = 9; CLIDS Lecture 11 @ cs huji 2013

type name = value; Ex6 - Variables Defining primitive variables: agrees with the type Can be: a number Existing initialized variable int a = 9; int b = a; CLIDS Lecture 11 @ cs huji 2013

Ex6 - Methods May contain: Local variable declaration s Local and members variable assignments Call to another function If\while blocks Return statements CLIDS Lecture 11 @ cs huji 2013

Ex6 – Thoughts about the design Parser – can tell whether line is legal (for example, no “;”), and identify the type of the line: New member/local variable? Call to a method? Method definition? Starting a block? … Check the validity Expressions – define a method, call to a method, define a variable… Variables – each variable has a different regular expression. Where do we check if\while blocks? CLIDS Lecture 11 @ cs huji 2013

Ex6 – should it compile or not? Run school solution! ~/bin/ex6school file.sjava Think java Ask in the forum CLIDS Lecture 11 @ cs huji 2013