Day 3: The Command and Visitor Patterns. Preliminaries The Java static type system uses simple rules to infer types for Java expressions. The inferred.

Slides:



Advertisements
Similar presentations
Java Programming Abstract classes and Interfaces.
Advertisements

SUMMARY: abstract classes and interfaces 1 Make a class abstract so instances of it cannot be created. Make a method abstract so it must be overridden.
Problem Solving 5 Using Java API for Searching and Sorting Applications ICS-201 Introduction to Computing II Semester 071.
INTERFACES IN JAVA 1.Java Does not support Multiple Inheritance directly. Multiple inheritance can be achieved in java by the use of interfaces. 2.We need.
Computer Science 209 Software Development Equality and Comparisons.
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.
IntroductionIntroduction  Computer program: an ordered sequence of statements whose objective is to accomplish a task.  Programming: process of planning.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Searching. 2 Searching an array of integers If an array is not sorted, there is no better algorithm than linear search for finding an element in it static.
Searching and Sorting I 1 Searching and Sorting 1.
Unit 261 Introduction to Searching and Sorting Comparable Interface Comparator Interface Algorithm Complexity Classes Exercises.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
Pointer. Warning! Dangerous Curves C (and C++) have just about the most powerful, flexible and dangerous pointers in the world. –Most other languages.
Java Generics. 2 The Dark Ages: Before Java 5 Java relied only on inclusion polymorphism  A polymorphism code = Using a common superclass Every class.
ICS201 Lecture 20 : Searching King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department.
Hash Tables1 Part E Hash Tables  
Data Abstraction and Object- Oriented Programming CS351 – Programming Paradigms.
Comparing Objects in Java. The == operator When you define an object, for instance Person p = new Person("John", 23); we talk about p as if its value.
Day 4 Objectives Constructors Wrapper Classes Operators Java Control Statements Practice the language.
01- Intro-Java-part1 1 Introduction to Java, and DrJava Barb Ericson Georgia Institute of Technology June 2008.
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.
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
Operator Precedence First the contents of all parentheses are evaluated beginning with the innermost set of parenthesis. Second all multiplications, divisions,
Georgia Institute of Technology Introduction to Java, and DrJava Barb Ericson Georgia Institute of Technology Aug 2005.
CSC Java Programming, Fall, 2008 Week 2: Java Data Types, Control Constructs, and their C++ counterparts, September 4.
Lecture 2 Object Oriented Programming Basics of Java Language MBY.
0 REVIEW OF HASKELL A lightening tour in 45 minutes.
CS 106 Introduction to Computer Science I 04 / 20 / 2007 Instructor: Michael Eckmann.
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.
JAVA 0. HAFTA Algorithms FOURTH EDITION Robert Sedgewick and Kevin Wayne Princeton University.
CS 112 Department of Computer Science George Mason University CS 112 Department of Computer Science George Mason University Final Review Lecture 14.
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.
TeachJava! 2003 Corky Cartwright Dung Nguyen Stephen Wong Charlie Reis, James Hsia, Neal Hororwitz, Peter Centgraf.
Java Programming Java Basics. Data Types Java has two main categories of data types: –Primitive data types Built in data types Many very similar to C++
TeachJava! 2003 Corky Cartwright Dung Nguyen Stephen Wong Charlie Reis, James Hsia, Neal Hororwitz, Peter Centgraf.
TeachJava! 2004 Corky Cartwright Dung Nguyen Stephen Wong James Hsia, Elspeth Simpson, Matthias Ricken, Dan Smith.
JAVA COURSE 1 Computer Engineering Association. Compile your first program Public class Hello{ public class Hello(){ System.out.println(“Hello”); } puclic.
Abstract Classes and Interfaces Chapter 9 CSCI 1302.
CS 61B Data Structures and Programming Methodology July 2, 2008 David Sun.
CMSC 341 Java Packages, Classes, Variables, Expressions, Flow Control, and Exceptions.
School of Computer Science & Information Technology G6DICP - Lecture 4 Variables, data types & decision making.
U n i v e r s i t y o f H a i l 1 ICS 202  2011 spring  Data Structures and Algorithms 
Chapter 7: Class Inheritance F Superclasses and Subclasses F Keywords: super and this F Overriding methods F The Object Class F Modifiers: protected, final.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Java Classes Chapter 1. 2 Chapter Contents Objects and Classes Using Methods in a Java Class References and Aliases Arguments and Parameters Defining.
Interfaces and Inner Classes
Java Programming, Second Edition Chapter Twelve Advanced Inheritance Concepts.
TeachJava! 2003 Corky Cartwright Dung Nguyen Stephen Wong Charlie Reis, James Hsia, Peter Centgraf.
Spring 2009 Programming Fundamentals I Java Programming XuanTung Hoang Lecture No. 8.
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
Reference Types CSE301 University of Sunderland Harry R Erwin, PhD.
Object Oriented Programming Lecture 2: BallWorld.
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.
Secure Coding Rules for C++ Copyright © 2016 Curt Hill
Searching.
Strings, StringBuilder, and Character
A lightening tour in 45 minutes
Primitive Types Vs. Reference Types, Strings, Enumerations
.NET and .NET Core 5.2 Type Operations Pan Wuming 2016.
null, true, and false are also reserved.
Introduction to Java Programming
MSIS 655 Advanced Business Applications Programming
Introduction to Java, and DrJava part 1
Introduction to Java, and DrJava
Searching.
Chap 2. Identifiers, Keywords, and Types
Introduction to Java, and DrJava part 1
Presentation transcript:

Day 3: The Command and Visitor Patterns

Preliminaries The Java static type system uses simple rules to infer types for Java expressions. The inferred type for an expression is conservative; it is guaranteed to be correct, but it may be weaker than what is required for a particular computation. Example: recall the finger exercise from Day 1 involving the DeptDirectory class hierarchy. Given a variable d of type Cons bound to a directory containing two entries, the expression d.getRest().getRest() is ill-typed. Why?

Explanation The variable d has type Cons which supports the method getRest. What is the type of d.getRest() ? The return type of the method getRest, which is DeptDirectory. Does DeptDirectory support the method getRest ? No. Hence, the method call ( d.getRest()).getRest() is not well-typed.

Casting: The Standard Work-Around Java allows any expression of object (reference) type A to be cast to another object type B --provided that the types A and B overlap (have a non-empty intersection ignoring null. Given a Java expression e of type A, the notation (B)e means expression e of type B. The value of e is unchanged.

Finger Exercise In DrJava, open the file DeptDirectory.java from the code library at the TeachJava website. Compile it. In the Interactions pane, evaluate: e1 = new Entry("Corky","DH3104","x 6042"); e2 = new Entry("Matthias","DH3106","x 5732"); d = new Cons(e1, new Cons(e2, new Empty())); d d.getRest() e = (Cons) d.getRest() e.getRest()

More Practice with the Composite and Interpreter Patterns In DrJava, open the file IntList.java. We want to convert IntList.java to a program List.java that implements heterogeneous lists (lists that can hold arbitrary objects, not just elements of a particular type). The element type in the program List.java must be Object. Otherwise the code is unchanged. Rewrite the concat and rev methods for heterogeneous lists. Test your code on some lists of Integer.

List abstract class List { abstract Object getFirst(); abstract List getRest(); abstract String toStringHelp(); } class Empty extends List { static Empty ONLY = new Empty(); // singleton pattern private Empty() {} Object getFirst() { throw new IllegalArgumentException( "first requires a non Empty List"); } List getRest() { throw new IllegalArgumentException( "rest requires a non Empty List"); } public String toString() { return "()"; } String toStringHelp() { return ""; } } class Cons extends List { Object first; List rest; Cons(Object f, List r) { first = f; rest = r; } Object getFirst() { return first; } List getRest() { return rest; } public String toString() { return "(" + first + rest.toStringHelp() + ")"; } String toStringHelp() { return " " + first + rest.toStringHelp(); } }

Discussion Question We want to define a method to sort heterogeneous lists. The method should work on lists of Integer, Double, Float Long, Short, Byte, Char, String, etc. How can we do this?

Some Possible Answers Pass the comparison method as an argument to the sort method. How can we do this? We will discuss a pattern for doing this later. Exploit an interface in all of the built-in types with a sensible total ordering called Comparable.

Java Interfaces In Java, an interface is a language construct that resembles a "lightweight" abstract class (an abstract class with no concrete methods). An interface definition has the syntax interface { } which looks exactly like a class definition except for the use of the keyword interface instead of class. But the members of an interface are restricted to abstract methods and static final fields.

Examples The interface Comparable is built-in to Java (part of the core library java.lang ) has the following definition interface Comparable { int compareTo(Object other); } The value returned by compareTo is negative, zero, or positive depending on whether this is less than other, equal to other, or greater than other. The built-in class String also implements the interface CharSequence which includes methods such as int length(). The built-in class StringBuffer (mutable strings) also implements this interface.

Writing a Sort Program Our task is to add a method List sort() { … } to the List class. We will decompose this problem into smaller tasks. Our first subtask is to write a method List insert(Object o) { … } that inserts o in proper order in this assuming that this is in (ascending) sorted order. Your code will be littered with casts. Our remaining task is to write sort() using insert as a help function.

List Sort abstract class List { abstract Object getFirst(); abstract List getRest(); abstract List insert(Object e); abstract List sort(); abstract String toStringHelp(); abstract List sort(); } class Empty extends List { static Empty ONLY = new Empty(); // singleton pattern private Empty() {} Object getFirst() { throw new IllegalArgumentException( "first requires a non Empty List"); } List getRest() { throw new IllegalArgumentException( "rest requires a non Empty List"); } List sort() { return Empty.ONLY; } List insert(Object e) { return new Cons(e,Empty.ONLY); } public String toString() { return "()"; } String toStringHelp() { return ""; } }

List Sort class Cons extends List { Object first; List rest; Cons(Object f, List r) { first = f; rest = r; } Object getFirst() { return first; } List getRest() { return rest; } List insert(Object e) { Comparable ce = (Comparable) e; Comparable cf = (Comparable) first; if (ce.compareTo(cf) < 0) return new Cons(e,this); else return new Cons(first, rest.insert(e)); } List sort() { return rest.sort().insert(first); } public String toString() { // no leading space before first return "(" + first + rest.toStringHelp() + ")"; } String toStringHelp() { // leading space before each elt return " " + first + rest.toStringHelp(); }