CIS 67: Program Design and Abstraction
Class Log Spring 2007
- 04/25/2007 - Class on 04/26/2007 - Last class
- The common cis67 final exam will be on May 9th from 2:00pm to
4:00pm in Barton Hall(BB) 201
- Returned and discussed the last five minute quiz
- Abstract methods and abstract classes. For example
Number is an abstract class with subclasses like
Byte,Double, Float, Integer, Long, Short. Remember: Abstract classes are used as
roots of a hierarchies of related classes. Concrete classes that extend an abstract class must
have only concrete methods.
- Remember the distinction shallow vs deep clone and equals.
- Remember for class constructors: if no constructor is defined, then
default is available; if some constructor is defined then you must define
also the default; constructors are not methods - they return no value and
they are not inherited. The copy constructor is a constructor that, given an
instance of the class, returns a copy of that instance. Who defines this constructor will choose if
to make a deep or shallow copy of the instance.
- Review: Exceptions
- Review: Two dimensional arrays
- Programming by Contract.
- Basic concepts in Object Oriented Programming: Encapsulation,
Abstraction, Inheritance, Polymorphism.
- Reasoning about programs: preconditions, postconditions, invariants, program complexity.
- Stubs and drivers.
- Testing vs debugging.
- Errors: Syntactic, semantic, logical, runtime.
- Review: Scope of identifiers. Visibility.
Allocation on the stack vs. dynamic allocation.
Parameter passing.
- Single vs multiple inheritance.
- Remember that object references are references.
Thus different variables may denote the same object and "=="
compares the references, not the objects being referenced.
- The type of a reference (static type, compile-time type) vs the type of the referenced
object (dynamic type, run-time type) = Dynamic binding = Lazy binding.
- Review: Arrays are objecs. There are no multidimentional arrays,
instead we have arrays of arrays, which can be jagged.
- We now know how to solve simple problems with programs. At a more
advanced level, we have started to understand the problems of software
development, debugging and testing, and some Object-Oriented Programming:
Abstraction, Encapsulation, Inheritance, and Polymorphism.
- 04/23/07 - Class on 04/24/2007
- Reviewing primitive types.
Representation of int
and byte. Automatic conversions among primitive types.
- Instance methods of a subclass can override the corresponding instance methods of
the base class and be invoked depending on the dynamic type of the objects it is applied to.
But (obviously) static methods are invoked according to static types.
- Covariant return type: in Java 5 in a subclass if a method moo in the subclass
overrides a method moo in the base class, moo in the subclass can return a type that is a subclass of
the class returned by moo in the base class.
- Control statements
- We can write non trivial programs with what we know. For instance a
concordance program. And with a little more
effort and knowledge we could write a Sudoku solver.
- Final 5-minute
test.
- 04/17/2007 - Class on 04/19/2007
- Returned and discussed 5 minute test.
- If class A extends class B we say that A is a subclass of B, or that
B is a superclass of A, or that B is the base class of A.
- The class Object, in addition to equals, clone, and toString, as we have
already seen, it has the method getClass that returns the class of an object.
- The interface Cloneable - it has no method, but it allows
the Object.clone() method to do a field-by-field copy of its instances
- But implementing a correct
clone operation
is tricky.
- In a subclass we refer to the superclass as super. In fact we should start
a constructor of the subclass with a call to super(..). If we don't, the system
will invoke automagically the default constructor of the superclass.
- In the subclass we have all the data members of the superclass, plus perhaps,
locally defined data members. But beware about access: if the superclass's data
members have visibility private, we cannot get to them directly.
- A program that prints to the screen the
lines that contain a specified string.
- In order to sort Items, Item must implement the Comparable interface.
- The right way to write equals. Example for the
Fraction class:
public boolean equals(Object f) {
if (f == null) return false;
if (this.getClass() != f.getClass()) return false;
return (this.num*f.denom == this.denom*f.num);
}
In this way if a is a non null object and b is another object that is null,
a.equals(b) will work correctly and return false. Note however that
b.equals(a) will raise a NullPointerException - equals is not symmetric!
[Note that classes that are immutable, they are not cloneable since there
is no reason to clone them.]
Note that getClass is the right method. instanceof would give the wrong result.
- Review: expressions
- Note that given int[] x = {1,2,3}; and int[] y = {1,2,3}; a.equals(b) is false but
Arrays.equals(a, b) is true.
- For people who love challenges, here are some nifty assignments, the stuff to play with outside of course requirements.
- Remember, the instances of interfaces (and abstract classes) do not come about
through
constructors, but by assignments from instances of concrete classes that implement the
interface.
- In an interface we can define headers of methods and define constants.
- Remember that the primitive data types are not classes.
But we have wrappers for the primitive data types, classes like
Integer,
Double,
- The wrappers for primitive types: Integer, Double,
Character, Boolean, .. are
immutable. The method clone does not apply to them as you can see by their
API: they do not implement the Cloneable interface.
- 04/13/07 - Class on 04/17/2007
- An interesting link on
careers in CS
- Input and output of objects - the Serializable interface.
Here
is an example that shows how we can write in a single call
a Fraction, or an array of fractions, or an array list of fractions
to a binary file.
- Class Evaluation
- UML diagram with Object [concrete], Comparable [interface], Student [abstract], and
GraduateStudent[concrete]. The 'extends' relation and the 'implements' relation.
- More about ArrayList: converting to array, sorting that array.
The elements of the array must be objects of a class that implements the
Comparable interface by implementing the method compareTo.
- Reading from a file
(like this) a sequence of
integers and storing them into an ArrayList. Then moving them to an array, sorting them, and
printing them.
Beware: there may be zero or more integers on a line,
separated by blank characters.
- Tenth 5
minute test.
- Last homework.
- 04/11/07 - Class on 04/12/07
- Returned and discussed the nineth 5 minute test.
- Access control to class members. We have
4 different levels in access control. From less stringent to more stringent:
public, protected, package
private. Notice that package is the access control when we do not specify
access control! So access is (a) everywhere, (b) in current package + any subclass,
(c) only in current package, (d) only in the class.
- The final modifier. You saw its use with data members when defining constants.
You can also use it with methods and classes. For classes it means that it cannot be extended (look
for example at the API definitions of Integer, String, ..). For methods it means it cannot be
overridden in subclasses.
- Assume we want to define a new class of objects, Door, which has a cost,
a side, and a height. The side and height are expressed as Fractions, namely
fractions of an inch. So a side that is 6 feet and 3/4 inches is 291/4.
We want to see the data members, constructors, accessors, modifiers, standard
operations like equals, toString, clone, compareTo, help methods such as
cost per square inch .. - Note that for equals and clone we may choose
a deep or a shallow implementation.
- Rotating the elements of an array k positions to the left.
We use cleverly the method for
rotating the elements of an array.
- 04/05/07 - Class on 04/10/07
- Abstract methods and classes. An abstract class X can have
constructors but cannot use them to construct X objects! The classes we
have been defining were concrete.
- Here is an example
of an abstract class and of polymorphism.
- Interfaces. The Cloneable interface. The Comparable interface. A class can implement
more than one interface.
- We can determine if an object is an instance of a class using
the "instanceof" operator, as you see
here
- but usually we do not need to. There we see also the use of the method
"getClass" that returns a class!
-
Twelveth homework
- Nineth 5-minute
test.
- 04/04/07 - Class on 04/05/07
- Returned and discussed the eight 5-minute test.
- Repeated discussion of inheritance: how we extend a class, what is inherited,
what assignments are legal, static vs. dynamic type, polymorphism.
- 03/29/07 - Class on 04/03/07
- Packages and (sub)directories.
The main program uses a class
Moo defined in the subdirectory called test.
In the main program I put "import test.Moo;"
In the file Moo.java defined in the subdirectory test I have to
add the statement "package test;".
- Java is an Object Oriented Language: We have seen Abstraction
, Encapsulation, Overloading
and the signature of a method.
Now we start thinking about Inheritance and
Polymorphism.
- Every class extends the Object class.
- Assignments in the class hierarchy. An example showing how we can
move between the type Object and other types.
- The static vs the dynamic type of a variable. They are also called
compile time and run time types of the variable.
- Polimorphism: early binding = eager behavior = use of static type;
late binding = lazy behavior = using dynamic type.
- Some methods of the
Object
class: clone, equals, toString: Shallow vs. deep equals, Shallow vs. deep cloning.
- Diagrammatic notation for a class (from UML)
- Extending a class:
BankAccount extended by
SavingsAccount
- Eleventh
homework
- Eigth 5 minute
test
- 03/28/07 - Class on 03/29/07
- Returned and discussed the seventh 5 minute test
- Files: input vs. output, folders vs. ordinary files,
text vs binary files, sequential vs. random
access. We stick (mostly) to sequential text files.
- An example
of
reading a text file using Scanner
- We write to a file with a PrintWriter, PrintWriter pw = new PrintWriter(new
File("temp1.txt"));
- PrintWriter is just like System.out. On it we can apply print, prinln, and printf, in
addition to close.
- A random number
generator
- 03/22/07 - Class on 03/27/07
- Exceptions (in chapter 15). try .. catch .. finally .. throws .. throw ...
- Checked vs. non-checked exceptions.
Checked exceptions are exceptions that
we want to handle when they occur (for example IOException and FileNotFoundException)
while unchecked exceptions are exceptions that when they occur we want to get out and
modify environment or program (for example, ClassNotFoundException - something
wrong in environment; ArrayIndexOutOfBoundsException, ClassCastException -
usually there is a logical problem in my program, ..).
- You can declare your own exceptions
if you think that there are not enough predefined exceptions (but we do not do it in cis67).
- Exceptions propagate until caught or the program is terminated.
- Exceptions are objects. They are raised automagically by the system,
or thrown explicitly by a throw statement written by programmer.
Try..catch..finally. throws.
- Files, directories and ordinary files, text and binary files. We will only deal with
text files. We read them with a Scanner, Scanner sc = new Scanner(new File("temp.txt"))
- We already know Scanner. We just note that it is proper to close the files that we use.
- Text files are in Chapter 16 of the
textbook. You may find it useful to consult the slides for the textbook
(accessible from course's home page).
- Tenth homework.
You may find useful
this code
and this code
- Seventh 5-minute test.
- 03/21/07 - Class on 03/22/07
- Returned and discussed second
midterm.
- Specified insertion sort.
- Well, Java really already implements for us methods for sorting and
binary search as you can see.
But we want to learn the basics.
- 03/13/07 - Class on 03/20/07
- Second Midterm
- Ninth
homework.
- 03/13/07 - Class on 03/15/07
- Next Tuesday we are having our second midterm.
Study notes, tests, and the textbook as
indicated here
- Returned and discussed the sixth 5 minute test.
- Again, the wrappers for the primitive types: Integer, Double,
Character, .. Autoboxing and deboxing (unboxing).
- A few more words about ArrayList
- Program Understanding: We have discussed method preconditions and
postconditions, loop invariants, algorithm complexity.
- Review of terminology for classes and their methods: static vs
instance data members and methods; constructors, accessors/selectors,
modifiers/setters; drivers and
stubs; subject of a method invocation = a class name or an object reference.
- The lexicographic ordering of strings. The compareTo method.
- Just touching on inheritance and the Object class.
- The intent of the methods: equals, toString, clone.
Beware that the default for "equals" is just "==", the default for
"toString" is a string of the form "name@hexNumber", the default for
"clone" is a physical copy of the storage associated to the object being
cloned. You can look at this code to
see what are these defaults.
- Assigning an array vs cloning an array vs copying an array.
In the first case two variables denote the same array. In the second,
given a reference to an array, we return a reference to a new array that
is a copy of the first. For example:
int[] a = {1,2,3}; int[] b = (int [])a.clone();
System.out.println(a == b); System.out.println(Arrays.equals(a, b));
will print out "false" and "true".
In the third case, given two references to arrays
we copy some content from the first array to the second array.
Here is an
example.
- Specified bubble sort.
- 03/02/07 - Class on 03/13/07
- Data members of objects created with new are initialized with default values and so are
elements of arrays like new int[5].
- Documenting Java programs: the
javadoc tool. Here is an
example.
- Case Analysis: Problem Requirements, Analysis, Design and Algorithms, Implementation,
Testing
- System.arraycopy
- Arrays.equals
- Arrays.fill
- Beware that we may have null arrays and empty arrays.
- Parameter passing: Mode - in, out, inout
- Multi-dimensional arrays. Note that these arrays are jagged ..
See for example this
program.
- Arrays, once allocated, are with unchangeable size.
ArrayList is a class
that can contain a variable number of elements. Unfortunately this convenience comes with a number of
difficulties. First, the elements must be references; second, we encounter for the first time the use
of generics.
- Homework 8
- Sixth 5
minute test.
- 03/02/07
- The week: Monday March 5 to Friday March 9 is Spring Break.
- 02/27/07 - Class on 03/01/07
- Returned and discussed 5-minute test.
- When writing a method or a class always think of how to test it, i.e. to make sure
that it really works.
- We have discussed the idioms for building a string using the idiom s1
+= c, where s1 is a String and c
a character; or the idiom s2.append(c), where s2
is a StringBuilder and c is a character.
- We know about about constructors, accessor/selectors,
modifiers/mutators, behavior and help/auxiliary methods.
- We have discussed parameter passing. All parameters are passed by
value (Remember, for reference types we pass the reference, not the
object.) and this has consequences on what can and cannot be modified.
We have seen that methods can have or not parameters, return or not
values, for a total of four cases.
- We have mentioned that methods may be overloaded (they may be with same name and
different signatures [method name plus, in sequence, the types of its formal parameters].
- Enhanced for loop: for (type variable: "linear"object) S;
- Specified and implemented a static method to sort an array
(selection sort).
- Specified and implemented a static method to do a binary search on a sorted array.
5A
- 02/22/07 - Class on 02/27/07
- Formatted output with printf.
Here is an example of
using formats.
- Errors: syntactic, semantic, logical; compile time vs. runtime.
- The order of evaluation of conditions matters. Suppose we are looking
for people who are young and rich and we are told that 50% of the people are
young and 5% are rich, what should we test first, for youth or for wealth?
- Some simple methods on arrays: finding an element, average of values in an array, ..
- public static void main(String[] args) : command line parameters.
- Reasoning about programs: Preconditions, postconditions, loop invariants.
- The StringBuilder class: strings that are mutable.
An example.
- Seventh Homework
- We have a 5 minute test
- 02/20/07 - Class on 02/22
- Returned and discussed the fourth 5 minute test.
- One dimensional arrays can be assigned; they can be compared (on the
basis of their addresses); they are object references;
the order of an array (i.e. the number of elements in the array)
can be known either at compile or at run time;
we can initialize an array with an aggregate (something
like {7, 11, 4, 2}).
- Finding the largest element in an array, reversing the content of an array.
- Given a string s representing an integer we
can also write a method ourselves to
convert the value to an integer.
- Given an int variable x with value, say, 358, we
compute its
value, without using Java API, as a string in decimal notation, in octal notation, in
binary notation, and, why not, in hexadecimal notation!
- 02/17/07 - Class on 02/20
- Computing the square root
of a number. Remember that it is unsafe to compare real values for equality. Check
instead if they differ by some small epsilon. The scientific notation, for instance
1.0e-12.
- Trivial introduction to exceptions: if we try to use a reference that is null,
our program terminates with a funny message about "NullPointerException"; similarly if we use
nextInt() to read an integer and we find a string somethink like "rose" instead, we get a
message about "InputMismatchException". Welcome to the world of exceptions.
If we do not want to see ou program crash, as seen above, we need to use some new constructs
as you can see in
this example.
- The reference classes corresponding to the primitive data types: Integer, Double,
Boolean,.. These classes are often called "wrapper classes".
- Conversion between the primitive types and the corresponding classes: autoboxing
and unboxing.
- Integer.parseInt .. Double.parseDouble
- The switch statement (case:, default:, break;);
- The encode function for the homework.
- One dimensional arrays: their components are accessed
by subscripting.
- The sixth homework.
- The fourth 5-minute test.
- 02/13/07 - Class on 02/15/07
- Returned and discussed the first midterm.
- You may find interesting and useful the
following discussion.
- Review of what is the syntax of expressions.
- More expressions: assignments seen as expressions; the conditional expression.
- Review of the scope of a variable.
- Method stubs, method/class drivers
- The textbook comes with
slides
- 02/07/07 - Class on 02/13
- 02/06/07 - Class on 02/08/07
- Returned 5 minute test
- Next Tuesday we have the first midterm.
Read your class notes, the
homeworks, and the textbook as indicated
here.
- The composite assignments +=, -=, *=, /=, ...
- Defining constants: static and final. See for instance the
definition of Math.PI.
- Loops terminated by a sentinel value
- We know what are method calls, formal parameters, actual
parameters.
Parameters are passed by value: in the case of primitive types, the value
of the variable (an int, or a double, or ..) is copied to the method; in the case of
reference variables, the value of the reference, not the object being referenced
is copied to the method. Trouble writing a "swap"
method.
- We have repeated the distinction between static and instance
attributes (data members), static and instance methods.
- The boolean operators && and || have a shortcut evaluation (also called
"conditional and" and "conditional or").
Instead & and | always evaluate their arguments.
- More about String: there is a big
difference between Strig s1 = null; and String s2 = ""; The first is a null
reference, not addressing any object. The second is a reference to an object, a
String, whose value is "". If I say s1.length() I get an exception; if I say
s2.length() I get 0.
- More discussion on strings. Given a string, produce string obtained by replacing
substrings with other substrings. Count the number of occurrences of a string in
another.
- Review of syntax seen up to now.
- 02/01/07 - Class on 02/06/07
- We repeat the meaning of "this".
-
Integer codes of the ASCII characters
and covenient methods in the Character class
- We have seen that we can have overflow and roundoff
errors.
- We have seen that the initial value of an object reference is "null"
for non-local variables (i.e. for data members) but undefined for
local variables. Similarly for data members that are of primitive types, they are
given a default initial value (0 for numeric types); but local variables with
primitive types are with undefined content.
- Continuing with String: compareTo, compareToIgnoreCase, toUpperCase,
toLowerCase. Be careful when using strings
- Notice that there are multiple methods for a name,
but they differ in their parameters. We say that the name of these methods is
overloaded. Note that we have not studied StringBuilder.
Signature of a method.
- For Scanner we have used the methods nextLine, nextInt, and nextDouble. But there is also
the method next that retrieves a token (a maximal sequence of non-white characters). We have created
a Scanner with new Scanner(System.in). We can also be given a String s and we can create the Scanner
ss = new Scanner(s). Then we can use ss to extract integers, reals, tokens from the string s.
- Third 5-minute test.
- Fourth homework
- 01/30/07 - Class on 02/01
- Returned and discussed the second 5-minute test.
- Conditional statements (but not switch): various forms of if
statement.
- Loop statements: while, for.
- The break and continue statements.
- We have used in a very primitive way strings and input and output streams.
- We have seen some methods of the String class: length, charAt,
indexOf, substring. Remember, Strings are immutable: there is
no way to change in place the content of a String. Garbage collection.
- 01/25/07 - Class on 01/30
- Our new TA assistant in section 1 is Michael Rothschild. Section 1 will meet in CC 104,
not CC200.
- A movie
about teaching and understanding.
- You can compute the binary (really, hexadecimal) representation of
integers
and of reals
- Abbreviations: ++, --, +=, -=, *=, /= ...
- Expressions, operator precedence
- Handed out, discussed, and partly coded the third homework
- Computing the gcd with uclid Algorithm
- Determining if an integer is a prime.
- Second 5
minute test.
- 01/24/07 - Class on 01/25
- Returned the first 5-minute test.
- Methods can have parameters and return a value.
- Making Scanner sc = new Scanner(System.in); a static data member of
the Fraction class.
- We have seen in the case of Fractions the difference between == and
equals.
- We have reviewed the primitive data types. We know various integer types,
real types, booleans, and characters. In terms of automatic conversion we
have, double above float; float above long, long above int, int above char
and short, short above byte.
- We have seen how integers are represented. We have seen how floating point
(real) numbers are represented (double represented as:
sign*mantissa*2exponent,
where mantissa is the value of the number normalizedto be of the form
0.mostSignificantDigitXXXX.
In double sign=1 bit, mantissa=52 bits, exponent=11
bits with a bias of 1023; in float sign=1 bit, mantissa=23 bits, exponent=8 bits).
For example here are some representations of float values in hexadecimal:
0.000000 with representation 0,
1.000000 with representation 3F800000,
2.000000 with representation 40000000,
0.500000 with representation 3F000000,
-1.000000 with representation BF800000.
Don't worry: I will not ask about their
representation in exams. But it is stuff you will meet again in other courses
like cis72 and you will need to know in your professional life.
- Java has a peculiar way of dealing with things like 1.0/0.0 and 0.0/0.0
as you can see
- We have seen assignments, automatic conversions, and the use of casting.
- 01/18/07 - Class on 01/23
- We sort of know what are primitive data types (int, long, short, byte, double,
float, char, boolean), object references,
some declarations (variable declarations, simple classes, and methods),
executable statements (assignment, input, output, method call).
We need to go carefully again many times over this
material. But we should be able to write small programs consisting of one or two
classes.
- What we have found up to now in a class: comments,
static (or class) methods.
- We will see that a class has members. Some of them are data members (often called
attributes), others are
constructors, others are methods. We will see accessor and setter methods.
We will understand the qualifiers public and
private. We will understand the qualifier static.
- We have talked briefly of classes and instances but we will need to say
much more about them.
- We will discuss the Fraction class and give some of its code.
- We are doing chapters 2, 3, and 4!
- When uncertain, we try simple programs, we talk with our colleagues,
we ask the TA, we ask the teacher. And of course we first read the book.
- Handed out and discussed the second homework
- We will do the first 5
minute test. These tests will usually be done on Tuesdays.
- 01/17/07 - Class on 01/18
- Tuesday we did the first chapter.
- Today in the lab we got accounts, learned to write a trivial program, to compile and run
it, and to email it to the instructor.
- For people who want to download java to their computer,
I suggest to download from
http://java.sun.com/javase/downloads/index_jdk5.jsp
the download called JDK 5.0 Update 10. You will then choose the version appropriate for you
platform (windows or linux).
- Now we jump semi-blind through the second, third, and fourth chapters!
Don't be afraid: we will go over this material many times.
- We have seen where to find information about Java's classes:
http://java.sun.com/j2se/1.5.0/docs/api/.
- Looking at your first homework: syntactic elements.
- What we find in a java source file: comments, [package statement],
import statements, public class with same name as file, possibly private
classes.
- Keywords and identifiers.
- Primitive data types: int, long, short, byte, double, float, boolean,
char,
Reference types.
-
Here
are the code conventions recommended for Java. It is probably more than
what you need, but it is a good reference nonetheless.
- Object orientation: Classes and their instances. The
Fraction example.
- Looking back at things we have already seen: methods, method
invocation, variables.
- Our 5-minute tests will be on Tuesdays (unless told differently
in
advance). So our first test will be next Tuesday
- 01/15/07 - Class on 01/16
- We go over the syllabus in its various aspects, objectives of the course,
people involved, text book, grading, etc.
- We discuss what is a computer system, with its CPU, main memory, secondary storage,
bus, input, and output. We mention things like bytes, megahertz, nanoseconds, ..
- We discuss Java and see why it is "write once, run anywhere".
- Read Chapter 1.
- Anonymous test.
- First homework.
- Our first lab is Wednesday January 17. Time and place is specified in
syllabus.
In the lab we will hand out the accounts for the course. We will see how to log on
Unix and on Windows. We will see how to edit a text file, how to compile it, how to
run it. We will see how to send a program to the instructor using email.
- 01/08/07 - Before Class on 01/16/2007
- This is hard to do, since probably you will not look here until
after the first day of class. But if you can, try to review what you
learned in previous programming classes, if any. Start reading the first
couple of chapters of the textbook.
On the first day of class I will give you an anonymous
test. This test
will test how much you know entering the class and gives you a hint
of what you are expected to already know.
Notice that I have already posted your first homework.