Wednesday, July 4, 2007

Next Fall!?

here's my next fall, i intend on keepin the blog going!

http://docs.google.com/Doc?id=dftk7qwn_36fqqwxz

Saturday, April 14, 2007

Lecture 30

Sorting an array of strings
for strings you can't use < , >
there exists a method called compareTo() which returns an integer
String x;
String y;
x.compareTo(y);
returns a negative number if x < y
returns zero if x == y
returns a positive number if x > y
String implements the comparable interface
public interface Comparable
{
public int compareTo(Object in);
}
Any class that implements comparable is strongly suggested to do it as follows
1. Total Ordering
- if a.compareTo(b) == 0;
then b.compareTo(a) == 0; (reflexive)

- if a.compareTo(b) <= 0;
then b.compareTo(a) >= 0; (antisymmetric)

- if a.compareTo(b) <= 0 and b.compareTo(c) <= 0
then a.compareTo(c) <= 0 (transitive)

a.compareTo(b) is defined for all a,b (Total)


2. If you implement equals() then if a.compareTo(b) == 0;
then a.equals(b) == true
and vice versa


Searching a sorted list
Sorted list searching can be done recursively with the divide and conquer strategy

Strategy
- split the list in half
- Let s represent the list item at the split point
if list has size > 1
if s = i, return index of s
if s > i, search the list segment with smaller values
if s < i, search the list segment with larger values
if list has size 1
if s = i, return index of s
otherwise i is not in the list
eg/ return -1

Tuesday, April 3, 2007

Lecture 29

QuickSort

  • somewhat trickier than MergeSort
    • join is trivial
    • all the action happens in split
  • in QuickSort , split sorts the elements into bins
  • all the list elements less than the given number is the 'pivot'
  • all the list elements Greater than a given number
  • all list elements equal to the pivot
  • choose the pivot arbitrarily from one of the list elements

eg

493872

choose 4 as pivot

low - 3,2
high - 9,8,7
pivot - 4

concatenate the list in order

sort(low)
sort(pivot + high)

  • pivot list is guaranteed to have at least one element(the pivot)
  • i want both split lists to be smaller than the initial list
    1. low list is non empty
      1. split between low and pivot
    2. if low is empty but high is not
      1. split between pivot and high
    3. if both low and high are empty then split somewhere in middle of pivot

Lecture 28

Sorting

  • A fundamental task of computer science
  • given an array , put the array in order
int a[]= {3,9,0,2,6}
sort(a);
a=0,2,3,6,9

Sorting Strategies

  1. Bubble Sort
    • take the unsorted array and start at the top
    • traverse the list until you find an element out of order
    • using pairwise exchanges move the out of order element toward the top of the list until it is in order
    • continue until the end of the list
    • once an out of order element is found we float it to the correct position
Example

  1. 39026
  2. 30926
  3. 03926
  4. 03296
  5. 02396
  6. 02369
Divide and Conquer Sorting

  • nobody uses bubblesort for anything serious
  • better methods:
    • mergesort
    • quicksort
  • if the list is of size > 1 then
    1. divide the list into two sublists
    2. sort each sublist
    3. join the two sublists
  • else
    1. do nothing
  • these are recursive sorting algorithms
  • all the actio nhappens in the splitting and joining
public static void Sort(int[]a, int begin, int end)
//sorts the subvector of 'a' from beginning to end inclusive
{
if (end - begin > 0)
{
int S = split(a,beginning,end)
sort(a,begin,S);
sort(a,S+1,end;
join(a,begin,S,end)
}

  • MergeSort
    • split is simple
    • join is complicated
  • QuickSort
    • split is complicated
    • join is simple

MergeSort
  • Split
    • splits the list down the middle
    • returns (begin + end )/ 2
  • Join
    • two sorted Lists
    • merge them in order

Example

038249
038 249
0<2
2<3
3<4
4<8
8<9
023489


42091

420:91
  • 42:0
    • 4:2
    • 4 //done
    • 2 //done
      • join(2,4)
        • 24
          • join(24,0)
            • 024
  • 9:1
    • 9 //done
    • 1 //done
      • join(9,1)
        • 19
  • join(024,91)
    • 01249

Lecture 27

Stacks and queues
  • best implemented with linked lists
  • trying to implement with arrays or arraylists is not feasible

Doubly Linked Lists
  • in a double linked list keep track of
    • head
    • next pointer in each node
    • tail
    • previous pointer of each node

public class DoubleLinkedList
{
public class ListNode
{
private myObject item;
private ListNode next;
private ListNode prev;
public ListNode {...}
}
public void addNode(MyObject, int)
public void delNode(int)
public myObject getData(int)

public void addNodeToHead(MyObject a)
public void addNodeToTail(MyObject b)
public void delNodeFromHead()
public void delNodeFromTail()
public MyObject getDataFromHead()
public MyObject getDataFromTail()



Adding a Node to A Position

//ListNode c = a.next;
b.next = a.next;
b.prev = a;
(a.next).prev = b;
a.next = b
//c.prev = b;
if (a==tail)
{tail=b;}


More Formally

//Check whether a exists

if (a != null)
{
b.next = a.next;
b.prev = a;
a.next = b;
if (a==tail){tail = b;}
else{
(b.next).prev = b
}

Deleting a Node From a Given Position

if(a.next)!= null
{
if (a.next = tail)
{a.next = null;
tail = a}
else{
a.next = (a.next).next
(a.next).prev = a;
}
}

Doubly linked list with stacks and queues

  • Stack
    • add
    • addNodeToHead(MyObject)
    • delete
    • getDataFromHead()
    • delNodeFromHead()
  • Queue
    • add a
    • addNodeToHead(MyObject)
    • delete / leave
    • getDataFromTail
    • delNodeFromTail()

Lecture 26

Linked Lists Continued

Node Inner Classes

  • ListNode has no use or meaning apart from the linked list
  • our existing definition opens the list to privacy leaks
  • a careless application programmer could get a reference and change it
  • make ListNode an inner class within the 'linked list' class
    • advantages
      • eliminates privacy leaks
      • simplifies LinkedList
    • disadvantages
      • reduces flexibility
Example

public class LinkedList inner
{
private class ListNode // inner class
{
private myObject item;
private ListNode next;
public ListNode(MyObject item, ListNode next) { ... }
}
private listNode head; ...}

  • using myObject as a generic
    • linked lists with generics
public class LinkedList inner //good

{
private class ListNode /** this is good, but this alone does not suffice */
{
private T item;
private ListNode next; // bad
private ListNode next; //good

  • use the generic type parameter firstly with the outer class as well as the inner class
  • use the generic type parameter with every declaration of the generic object.

Lecture 25

Recursion

  • Stack
    • space for parameters / local values/ return values
  • indirect recursion
    • a method which calls iteself with different parameters
  • recursion
    • a method which calls itself within itself
      • if this is done wrong you get a stack overflow error

int fact(int n)
{
//base case

if (n == 1) { return n}
return n * fact(n-1);
}

  • famous recursive methods
    • binary search
    • mergesort
    • quick sort
    • towers of hanoi

int bSearch(int[]A, int key, int l, int r)

{
// base case

if (l>r) return -(l + 1)
int m = (l + r) / 2;
if (A[m] == key ) return m;
if (A[m] < face="courier new">return bSearch( A, key, m+1, r)
return bSearch(A, key, L, m-1);

}


these were the notes i got when turnpin was in class, he doesn't write on the board too often so i hope this helps.

Tuesday, March 20, 2007

LabTest 3 Impressions

Hey Guys,
I wrote the test yesterday, relatively hard, wish i studied JUST linked lists instead of the gui and recursion.
turns out the only thing on the test was linked lists and generic class
the test before that (Monday) did linked list with an equals() method..

I found it pretty misleading of Andrew and Turpin to tell us it would cover everything when it ended up covering linked lists specifically.
worries me quite alot, because now i have no idea if i should believe them about exam materials, etc.

anyways we had to make a listNode class and a LinkedList class
make them work
using a generic object to carry data
then make a test program which proves that it works, using string and integer values.

later
Jake

Thursday, March 15, 2007

Lecture 24

Linked List
  • data structure containing nodes
  • each node points to the node after it

Adding nodes to the middle

  • find the index of the node prior to the one you must add

int position = i // position where the new node gives
ListNode a = FindNum(head, position - 1);
ListNode b = new ListNode();//new object
b.setNext(a.getNext()); // 1
a.setNext(b); //2

adding position 0 = creating a new head

listNode b = new ListNode();
b.setNext(head);
head = b;



Deleting Elements

  • deletion involves reordering next pointers

ListNode a = findNum(head, position - 1);
a.setNext((a.getNext()).getNext());

  • object must not be null
  • a.getNext must not be null

Linked List as Object

public class LinkedList
{
private ListNode head;
public LinkedList(ListNode head);
public LinkedList()
public ListNode findEnd()
public ListNode findNum()
public void addNode(ListNode, newNode, int position)
public void delNode(int position)
public void addNodeToEnd(Listnode, NewNode)
public int getSize()

Tuesday, March 13, 2007

Java Calculator GUI Lab

hey guys,
finally finished it and it works fine.. if you want some simpler code then what i'd seen on the other forum ... use mine.

i did all of this straight from the lecture notes so there shouldn't be anything too confusing
but i will admit it took me a WHILE to get this working.. rusty i guess.. heh..
later
Jake


import javax.swing.*;
import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.*;
import javax.swing.JFrame ;

public class MenuJFrame
extends JFrame
implements ActionListener
{
public static final int WIDTH = 600;
public static final int HEIGHT = 400;

// without putting these here, they are unaccessable by the actionlistener
private JPanel westPanel;
private JPanel eastPanel;
private JTextField one;
private JTextField two;
private JTextField answer;


public MenuJFrame()
{
//main window

super("Java Calculator");
this.setSize(WIDTH,HEIGHT);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(new GridLayout(0,2));

//west panel

westPanel = new JPanel();
westPanel.setLayout(new GridLayout(3,0));
this.add(westPanel);

//east panel

eastPanel = new JPanel();
eastPanel.setLayout(new GridLayout(4,0));
this.add(eastPanel);


//text fields

one = new JTextField(30);
two = new JTextField(30);


westPanel.add(one);
westPanel.add(two);

//answer

answer = new JTextField("0.0");

//non-editable text field

answer.setEditable(false);
westPanel.add(answer);

//buttons for east
JButton add = new JButton("+");
JButton subtract = new JButton("-");
JButton multiply = new JButton("*");
JButton divide = new JButton("/");

//add buttons to eastPanel

eastPanel.add(add);

add.addActionListener(this);


eastPanel.add(subtract);

subtract.addActionListener(this);

eastPanel.add(multiply);

multiply.addActionListener(this);

eastPanel.add(divide) ;

divide.addActionListener(this);

//Menu Bar

//create a new menubar , this is ONLY the grey bar at the top w/ nothing in it!!!
JMenuBar myMenuBar = new JMenuBar();

//this.setJMenuBar is a method which auto positions the menu bar @ the top
this.setJMenuBar(myMenuBar);

//create two fields, File and Clear.
JMenu File = new JMenu("File");

JMenu Clear = new JMenu("Clear");

//create a menuItem quit
JMenuItem quit = new JMenuItem("Quit");

//add action listener to quit, so the program quits when clicked
quit.addActionListener(this);

// add quit to the file menu
File.add(quit);

//create menu items for clearing the fields
JMenuItem clearA = new JMenuItem("Clear A");
JMenuItem clearB = new JMenuItem("Clear B");
JMenuItem wipe = new JMenuItem("Clear All");

//add action listeners for each
clearA.addActionListener(this);
clearB.addActionListener(this);
wipe.addActionListener(this);

// add all three menu items to the menu 'Clear'
Clear.add(clearA);
Clear.add(clearB);
Clear.add(wipe);

// add file and clear to the menu bar
myMenuBar.add(File);
myMenuBar.add(Clear);






}


//ActionListener


public void actionPerformed(ActionEvent e)
{
String cmd = e.getActionCommand();

//if the button is '+' then add the two fields and display answer in bottom box
if (cmd == "+")
{
answer.setText((Double.toString((Double.parseDouble(one.getText())) + (Double.parseDouble(two.getText())))));
}

//if the button is '-' then subtract the two fields and display answer in bottom box
if (cmd == "-")
{
answer.setText((Double.toString((Double.parseDouble(one.getText())) - (Double.parseDouble(two.getText())))));
}

//if the button is '*' then multiply the two fields and display answer in bottom box
if (cmd == "*")
{
answer.setText((Double.toString((Double.parseDouble(one.getText())) * (Double.parseDouble(two.getText())))));
}

//if the button is "/" then divide the two fields and display answer in bottom box
if (cmd == "/")
{
answer.setText((Double.toString((Double.parseDouble(one.getText())) / (Double.parseDouble(two.getText())))));
}

//if button is "Quit" then close the program
if (cmd == "Quit")
{
System.exit(0);
}

// if button is 'Clear A' then clear A
if (cmd == "Clear A")
{
one.setText("");
}

// if button is 'Clear B' then clear B
if (cmd == "Clear B")
{
two.setText("");
}

// if button is 'Clear All' then clear all fields and leave 0.0 in the answer field
if (cmd == "Clear All")
{
one.setText("");
two.setText("");
answer.setText("0.0");
}




}



}

public class JavaCalculator
{
public static void main(String[] args)
{
MenuJFrame MyWindow = new MenuJFrame();
MyWindow.setVisible (true);

}

}

Monday, March 12, 2007

Lab 4 and 5

Post your ideas / code / questions for these labs here

Friday, March 9, 2007

Lecture 23

Linked Lists

  • alternative method for producing an array of arbitrary size
    • a collection of objects of the same type
    • contained in the wrapper object, which points (or contains a reference) to the next object in the list
  • declare public class myObject
public class ListNode
{
private myObject item;
private ListNode next;
public ListNode(){...}
public ListNode getNext() {return next}
public void setNext(ListNode next) {this.next = next}
}

  • initially the list is empty
    • ListNode head = null;
  • add elements to the end as required
    • first element:
      • head = new ListNode(); /*head points to head of chain*/
    • every subsequent slement
      • let ListNode tail be reference to the last element in the list
        • tail.setNext(new ListNode(...));
        • tail = tail.getNext(); // not mandatory to keep track of tail
  • if the list is empty then the head must be 'null'
  • next pointer in the last element must be null

Transversing the List

  • Items are arranged in order
    • the only way to get something from the list is to first access all previous elements

Example - retrieve the ith element
  • pass through i next pointers to find the one you want

ListNode = head;
int j;
for (j=0; (j

Example - find the last element

ListNode n = head;
if (n != null)
{
while (n.getNext() ! = null)
{n = n.getNext() }
}


Lecture 22

Generic Methods


  • method with a type parameter
    • independent of a generic class
    • can be used in a non-generic class
    • can be used in a generic class with a different type parameter

public class myClass
{
public void myMethod(T x)
{
System.out.println(x);
}
}

  • syntax for calling the method
myClass m = new myClass();
m.myMethod("Hello");
m.myMethod(6);


Inheritance

  • inheritance is allowed with generics
public class Parent
{
}


public class Child extends Parent
{
public class A {...}
public class myGeneric
{...}
myGeneric//these two have
myGeneric//No Relationship

ArrayList
Example

Create an array of 5 Strings using ArrayList


ArrayList myList = new ArrayList(5);
// = generic type parameter

ArrayList myList = new ArrayList(0);//size is 0
myList.add("x"); // size is now 1
myList.add("y"); // puts y at index 1, size is now 2


Wednesday, March 7, 2007

Lecture 21

Generic programming
public class x
{
private String s;
public x(String s){this.s = s;}
public String getS(){return s;}
}
if we need many classes with the same function but different instance field type.
we can
1. declare them all individually
2. use a generic class(better)

a generic is a class that takes a type as a parameter

public class x <T>
{
private T s;
public x(T s){this.s=s;}
public T getS(){return s;}
}

x<String&lgt; myX = new x<String&lgt;("hello");

Note:
-constructor declared in the class as
public x(......)

but called as x<String&lgt;(....)
-The type associated with the generic can be any reference type
(i.e. any object type)

e.g. String, GregorianCalendar, JFrame and so on.

-Cannot use primitives
e.g. x<int&lgt; myX = new x<int&lgt;(36) is illegal

-There exist "wrapper" subjects for every primitive type.
int -&lgt; Integer
char -&lgt; Character
double -&lgt; Double
and so on...

x<Integer&lgt; myX = new x<Integer&lgt;(36); is legal

more illegal uses of the type parameter "T"

T myT = new T(); not okay
T[] myTArray = new T[10]; not okay

cannot create an array of generics.
x<String&lgt;[] myXarray = new x <String&lgt;[10] is illegal

can a generic take more than one type ?
the answer is yes.

public class TwoTypeGeneric <FirstType, SecondType&lgt;
{
codes here
}

restricting Types
you may wish to constrain the type parameter as follows
1.the child of a given class
2. implements a give interface
why?
can use methods associated with the ancestor/interface
usage: the extends keyword is used for both interfaces and ancestors.

Require that T implements myInterface

public class x<T extends myInterface&lgt;

require that T is a descendant of ancestor
public class x<T extends ancestor&lgt;

Also legal to require more than one
at most one is a class and the rest can be interface
_ use ampersands (&) to be seperator
T -&amp;lgt; descendant of class B
implement interface C,D
public class x<T extends B&C&D&lgt;

Monday, March 5, 2007

Lecture 20

Menus

  • Important classes are

    • JMenuBar

    • JMenu

    • JMenuItem

  • all three of these are children of Component

  • all implement the add() method



Creating a Menu

  1. Create a Menubar

    • JMenuBar myMenuBar = new JMenuBar();

  2. Create menus and add them to the menubar

    • JMenu = new JMenu(“File”);

    • MyMenuBar.add(myMenu);

  3. Create and add menu items to the menu

    • JMenuItem Save = new JMenuItem(“Save”);

    • MyMenu.add(Save);

  4. Add action listener to each menu item

    • Save.addActionListener(this);

  5. Add menuBar to the JFrame

    • add (myMenuBar);//Bad!!

    • Set JMenuBar(myMenuBar); // Good!!





Windows and Inner Classes



  • For Complicated window components it makes sense to use inner classes

Recall:

Public class OuterClass;

{

Private class InnerClass

{

}

}

  • A complicated panel within a JFrame

Public class myJframe extends JFrame

{

Public myJPanel()

{//appearance of the panel;}

}

Public JFrame()

{

Add ( new myJPanel());

}

Private class myJPanel extends JPanel implements ActionListener

{

Public myJPanel()

{

JButton b = new JButton(“Button”);

b.addActionListener(this); /* this refers to myJPanel*/

add(b);

}

Public void ActionPerformed(ActionEvent e){…}



Text Field

  • JTextField

    • Constructor takes an integer size argument

    • JTextField t = newJTextField(20); /* 20 chars wide*/

      • public String getText()

      • public void setText(String S)

      • public void setEditable(boolean e)



Wednesday, February 28, 2007

Lecture 19

JButton myButton = new JButton("x");
myListener m = new myListener;
myButton.addActionListener(m);
-------------------------------
/* can be replaced with
below */
-------------------------------
myButton.addActionListener(new myListener());


public myJFrame()
{
super("title of Window");
.
.
.
JButton myButton = new JButton("title of button");
myButton.addActionListener( new myListener());
}

What happens when you have multiple buttons?

  • Bad way
    • define different listener classes for each button
    • register the appropriate class to the appropriate button
  • Good way
    • examine e
      • object of type ActionEvent
      • ActionEvent has a method returning the label of the button pressed

public String getActionCommand()
/* Andrew drew a picture of two buttons labeled different things then pointed out that when you click the button "one" e.getActionCommand returns "One"*/

  • These implement the interface LayoutManager
    • BorderLayout
    • FlowLayout
    • GridLayout

  • A window (JFrame) is a container
    • allowed to contain objects and have layouts
  • a window can be divided into regions using LayoutManager
    • each region can be made into a container by declaring it a JPanel
  • a panel is a Container

  1. Declare a LayoutManager
    1. setLayout(new BorderLayout());
  2. Add a apanel to as many regions as you want
    1. JPanel myPanel = new JPanel();
    2. add(MyPanel, BorderLayout, North);
  3. Declare a layout to the panel
    1. myPanel.SetLayout(new.FlowLayout());

Monday, February 26, 2007

Lecture 18

  1. Create the component

  2. Create a listener

  3. Create an instance of the listener

  4. Add (“register”) the listener to the component

  5. Add the component to the JFrame



  • You can skip steps 2 – 4 if your program doesn’t require an action



  • How does this work?

    • Create a visual interface

    • A JFrame

    • A button

  • Then implement a listener

    • this is the code which you wish to perform once the button Is pressed

  • register the listener to the button

    • when the button is pressed

    • Java calls ActionPerformed

      • You do not call ActionPerformed

      • ActionPerformed is an automation in Java

  • Registration tells Java to call it when the button is pressed

    • And then reads the listener



Labels

  • can add a line of text using JLabel component

    1. create a component

    2. JLabel MyLabel = new JLabel(“My Label”);

    3. Skip

    4. Skip

    5. Skip

    6. Add the component to the JFrame

      • MyWindow.add(MyLabel);



Layouts

  • We require a way to arrange multiple objects within a window

  • Java technique which accomplishes that is the layout

    • BorderLayout

    • GridLayout

      • FlowLayout

  • JFrame contains a method setLayout()

  • MyWindow.setLayout(Layout l);

  • Executing this sets the layout of the window to the layout object l.

  • Andrew is not sure that setLayout take a Layout as its param, he will find out for next class

BorderLayout

  • When Adding a component also specify a region in which It goes

    • MyWindow.add(MyButton, BorderLayout.North/East/South/West/Center)



GridLayout

GridLayout GL;

GL = new GridLayout (2, 3)

//2 = rows, 3 = columns

MyWindows.setLayout(GL);

JLabel Label 1 = new JLabel (“1”)

MyWindow.add (Label 1);



Flow Layout

flowLayout FL;

FL = newFlowLayout ();

MyWindow.setLayout (FL);

// add components

Good JFrame Practice

  • Up to now, everything has been done in main

  • This is bad practice because the window is an object

  • It should be treated as such

  • We are creating a modification of JFrame

  • Use inheritance


Friday, February 23, 2007

Lecture 17

  • JFrame is the class that handles windows in Java
    • import 'javax.Swing.JFrame;
    • creating a window is equivalent to creating an object of type JFrame
    • JFrame has an extensive public interface

public void setSize(int width, int height)
public void setTitle(String title)
public JFrame(String title)
public void setVisible(boolean v)
public void add(Component x)

  • notice that the program didn't end when the window closes by default
  • default window close behaviour is to hide the window (but not exit the program)
  • we have to handle the event where the user clicks close

public void setDefaultCloseOperation(int x)
  • we can use
JFrame.EXIT_ON_CLOSE
JFrame.HIDE_ON_CLOSE
JFrame.DO_NOTHING_ON_CLOSE

  • These are given integer values (in order) 3,0,1
    • do not use these values as Java might change those numbers in an update


Action Listeners and Action Events

  • each component must register the listener that handles its events
  • Java interface ActionListener
    • event type is a class called ActionEvent
      • a listener you define must implement the interface ActionListener
public void actionPerform(ActionEvent e)
{

}

  1. Create the component
    1. JButton myButton = new JButton(" ");
  2. Write a listener class
    1. public void myListener implements ActionListener
      {
      public void actionPerformed(ActionEvent c)
      {
      }
      }
  3. Create an instance of the listener
    1. MyListener m = new myListener();
  4. register the listener with the component
    1. myButton.addActionListener(m)
  5. add the component to the JFrame
    1. myWindow.add(MyButton);

Wednesday, February 21, 2007

Finished Test 2 Impressions

Just wrote the test yesterday...
  • had to make an
    • abstract class
    • a child extended class from that class
    • an array which takes in args parameters and inputs them into the class
  • i found it to be somewhat simple
    • but the time we had i didn't feel was enough
    • and Andrew's API was quite unfinished
      • and seemed to have a typo in a method description in his API
    • being given a test that had to support an unfinished API
      • and had to start from scratch
    • was VERY difficult for me to get done
  • still felt the test was fair, for what it tested
  • but my advice to those who haven't written it
    • practice your speed
    • be sure of your coding practice

later
Jake

Lecture 16

  • polymorphism is a very powerful tool because many related classes can be handled the same way and through the same public interface.
  • java figures out which overridden method is the public interface to use

Student
  • Undergrad
  • Graduate
  • all 'students' have a routine for calculating letter grades

public string getLetterGrade()

public void printTranscript(Student s)
{
System.out.println(s.getLetterGrade());
}

  • u - undergraduate
  • g - graduate student
  • q - special student
    • these are all classes which have getLetterGrade overrides
      • print transcript(u)
      • print transcript(g)
      • print transcript(q)
Polymorphism and Arrays

  • consider an array of students
    • conglomeration of undergraduate students, graduate students and others.
  • how do we create the array?
Arrays vs. non-arrays
Student[] s; Student S;
s = new Student[5]; S= new Student(); // not legal


Graphical User Interfaces (GUI)

  • so for our programs we have started on the first line, gone through every line in sequence, and terminated at the end
  • windows does not work that way
  • the programmer doesn't determine the order of events
  • the program 'listens' for user-generated events and passes them to the event handler
  • A GUI program consists largely of event handlers that respond to events
  • you would almost never call event handler methods instead java calls them when the even happens

Monday, February 19, 2007

Lab Test 2 Impressions

Here you can post how you felt the test went, give pointers to those who haven't taken it and so on.

Lecture 15

Things to know for the next Lab:

Inheritance, Arrays, Interface

Things to know for the Midterm:


everything we have covered until this class (Feb 19 2007) is fair game for the midterm
this is unofficially true but the only thing Andrew has told pertaining to Test Content.


Aggregation
  • keeps a reference to an external object
  • external object outlives the aggregate
Composition
  • keeps a copy of object it contains
  • contained object lives and dies with the composition
Polymorphism and Arrays

public class Parent{}

public class Child extends Parent{}

Parent P;
Child c;
c = new Child();
p = c;

  • this is legal
  • P is a reference to C
  • P is of type parent
  • P is a reference to C and is treated like an object of type Parent
  • remember
    • C inherits all of P's methods
    • C can use anything inherited from P
      • public methods ...etc
  • but when p=c
    • p can only access inherited methods from C
      • in other words only methods which exist in both classes can be used in p
  • suppose C has an overridden method
public class Parent
{
public void myMethod()
{
System.out.println("parent");
}
}
public class Child extends Parent()
{
public void myMethod()
{
System.out.println("child");
}
}
-------------------------------------------------

Child c;
Parent p;
c = new Child();
p = c
c.myMethod(); /* prints "child" */
p.myMethod(); /* prints "child" */
  • p.myMethod prints "child"
    • this is because java remembers that P started out as C which is type child
      • this is called "Late Binding"
Summary

Child c;
Parent p;
c = new Child();
c.myMethod(); /* prints "child" because of overriding*/
p = c;
p.myMethod(); /* prints "child" because of polymorphism / late binding*/
p = new Parent();
p.myMethod(); /* prints "parent" because it is not an object reference anymore*/

Wednesday, February 14, 2007

More On Arrays

Review of Arrays

  • Declaring
    • double[] testmark;
  • Assign Space
    • testMark = new double[5]
  • Use Elements in Array
    • testMark[3] = 720;
  • an array is a table of values stored in memory
  • the array name (testMark) is a reference to the array, just like object references
  • to refer the ith member of the array
    • testMark[i]
  • Very Important
    • array indices start at zero, not one.
  • use testMark.length
    • length is the keyword to get the length of the array
  • arrays are objects
    • they should be treated as such
  • because we can change the elements of an array and because arrays are objects we have to treat them as mutable objects
    • deep copy, defensive copy
  • look again at testMark

double[]copyMarks; // create a copy of testMarks
copyMarks = testmarks //BAD!!!
  • both references (copyMarks and testMarks) point to the same thing
  • remember this also happens with object references
  • how do we create a copy of an array?
    1. allocate new space
    2. individually copy elements

testMark = new double[5]
int i;
for (i=0, i < testMark.length, i++)
{
copyMark[i] = testMark[i];
}
  • Summary
    • Arrays are mutable objects which means Defensive copying
    • copy on object containing an array
      • deep copy
    • so i do deep copy test mark
    • testMark == copyMark
      • this is not the same reference
    • unfortunately equals() does not exist for arrays
    • there exist java utilities for array equals
      • java.util.arrays
        • equals
        • fill
        • sort

Lecture 14

Midterm Feb 25 2007


Command Line Arguments

public static void main (String[]args)
{
}


  • argument passed to main is an ARRAY of STRINGS
  • args is an array of Strings consisting of arguments typed on the command line when Java was executed
console - java -cp . ArgsTest one two three
  • that is 3 arguments
    • one
    • two
    • three
      • NOTE: args are seperated by empty spaces, NOT COMMAS, i tested this code myself after class
  • how many parameters?
    • args.length
  • this is useful for automation and for quick input to a program
  • can you pass array objects to a method as a parameter?
    • yes
public void method (double[]myArray)
{}
  • can you return an array?
    • yes
public double[] method()
{
}
  • remember to defensively copy

Aggregates and Compositions
  • a composition is like an aggregate but stronger
  • here the parts only exist in the context of the whole and vice versa
    • a car is not a car without an engine
    • a book is not a book without pages
  • An aggregation relationship
    • aggregate does not keep a private copy of its member objects
    • refers to them by reference
      • investments which contain stocks
public class Investment
{
private Stock x;
private int num;
}
public class Stock
{
private String name;
private double price;
}

  • who creates the stock?
    • investments constructor should not create a stock
    • should already exist when Investment is created
  • should Investment keep a local copy of the Stock?
    • No
      • the stock is under outside control
  • stock outlives the Investment and exists outside the Investment
  • this is an aggregation
  • a composition relationship
    • private copies are kept
    • contained objects do not exist outside of the composition
    • objects live and die with composition
public class CreditCard
{
private String name;
private int cardNum;
private GregorianCalendar dateOfIssue;

//this is a composition relationship

Wednesday, February 7, 2007

Lecture 13

Inner Classes

  • an inner class is a class defined within another class

Example

public class outerClass
{
private class innerClass
{
}
}
  • inner classes provide extra 'class-like' functionality to your class
    • makes your class look self contained
  • inner classes have access to private members of the outer class
    • and vice versa
  • inner classes can be made public and are then visible outside of the outer class

Access

public class outerClass
{
private int y;
private int x;

private class innerClass
{
private int y;

public void method()
{x=0 //if no private member in inner class named x
}
}
  • if no private member in innerClass is named x , it can refer to x in the outer class by name
  • to gain access to the outer class y
    • outerClass.this.y

public class outerClass
{
private int x;
private int y;
private class innerClass
{
private int y;
public void method()
{
x = 0; // refers to the outerClass x
y = 0; //refers to the innerClass y
outerClass.this.y; // refers to outerClass y
}
}
}

  • creating a public Object of an inner class type
public class outerClass
{
public class innerClass
{
}
}
  • first create an object of type outerClass
  • then create an object of type innerClass
outerClass a = new outerClass();
outerClass.innerClass b = a.new innerClass();

Aggregates Compositions and Arrays


Arrays

  • in undergrad say we want to store the grades for all the term tests instead of just the final raw grade
  • an array lets us refer the collections of variables of the same type using a single name and number
Very Important

  • Arrays in java always have their first object at zero (0)
  • if you don't know the length of an array
    • all arrays have a special public field called 'length'
testArray.length
  • Alternative Array Declaration
    • (with initialization)
double[]testArray = {0.0,0.0,0.0,0.0,0.0}
  • this array has 5 elements

Monday, February 5, 2007

Lab 3

Please Post your ideas for Lab 3 here! I haven't started yet, my labs are on tuesday!

For Lab Instructions: Click

Friday, February 2, 2007

SSH Tips and Tricks

I'm tired of programming in prism, i want to program at home.

Andrew uses an SSH client in class to mimic a Linux environment in Windows and to access example files from his login...

I want to do this, but i don't know how!

I spoke to Andrew he said any SSH client will work (putty...etc)
and that everything has to be saved and edited at york to do it through that client

does anyone use SSH at home?
if so can you put the URL for YorkU's SSH portal in the comments of this post?
as well anything you know about SSH that others will find useful would be great...

Later
Jake

Lecture 12

Abstract Classes
  • Abstract class is a class that cannot be instantiated
    • only its children can be instantiated


Abstract Method
  • a method that is not defined in the abstract class
    • only its head is given

Interfaces
  • can be thought of as an extreme abstract class
  • used to group together classes with similar features into a 'type'
  • interfaces contain only abstract method headers
    • no instance fields
  • an interface is a description of how to interact with a group of related classes

Syntax

public interface myInterface

{
/*any method in here is abstract, it is assumed that it is abstract so you don't have to write the keyword 'abstract'*/

public void method(int a);
public int method2();
}

  • any class that implements the interface must override method, and method2

public class MyClass implements MyInterface
{

private int f;
public void method1(int a)
{

System.out.println(a)

}
public int method2()
{
return f;
}

}

  • you can create objects of type MyClass and treat them as type myInterface if necessary

public void interfaceMethod(myInterface in, int a)
{

int b;
in.method1(a);
b = in.method2();

}

  • it is possible to implement multiple interfaces

public class MyClass implements interface1, interface2
{
}

/* this would force MyClass to have all methods from both interface before it will compile */


  • it is possible to have inheritance within interfaces

public interface MyInterface

{

public void M1();
public void M2();

}

public interface myChild extends myInterface

{
public void M3();
}

  • a class that implements an interface but doesn't override one or more interface methods must be an abstract class
  • all unimplemented methods are automatically abstract

Wednesday, January 31, 2007

Lecture 11

Inheritance

  • Objects that inherit features of a parent class can be thought to contain an object of the parent type
  • all methods and fields of the parent are "inherited"

Best Practices With Inheritance
  • discard packaging
  • make all instance fields private
    • this means instance fields are not visible to child methods
    • if you need to access instance fields of the parent from the child use the public interface

Why Do This?
  • child inherits parent's methods and therefore inherits the public interface
    • this simplifies access
    • and prevents privacy problems via inheritance

public class Parent
{
protected mutable class x;
}

public class Child extends Parent
{public mutable class leakyMethod()
{return m;
}
}

Constructors
  • form part of the public interface

public class Child extends Parent
{
public child ( ...parameters for child / parent )
//call parent constructor
super(...parameters for parent)
//assigns child parameter
}


Overriding Methods

  • Child classes inherit all methods from the parent
  • child has the option to re-implement these methods
    • called overriding

Example
  • All objects extend type Object by default

public class MyClass [extends Object]
[
  • type object contains several default methods
    • equals(), toString(), clone()
]

  • declaration of an overridden method in the child must be exactly the same as the parent
    • same return type
    • same parameter type
    • same number of parameters

Parent

public int myMethod(double a, int b)

Child

public int myMethod(double a, int b)

  • if myMethod is overridden in a child class, use 'super.myMethod' to gain access to the parent method
  • to prevent overriding use 'final'


Abstract Classes

  • a student is either graduate or undergraduate
    • there is no 'plain' student
  • so it doesn't make sense to instantiate this class
  • all students have letter grades
  • child classes of student should be forced to implement getLetterGrade()

Solution

  • declare Student an abstract class
    • can't instantiate an object of type student
  • declare getLetterGrade() an abstract method within abstract class student
  • children must override getLetterGrade() or they will be abstract classes themselves

public abstract class Student
{
.
.
.
public abstract String getLetterGrade();

}

Tuesday, January 30, 2007

Lab Test 1 Finished Impressions

today I finished the LabTest
i found it difficult, it was basically like starting a half finished lab from previous weeks.
key things on it were

  • JavaDoc
    • know @param and @return
    • know /**, */ are the opening and closing parenthesis
  • Copy Constructors
    • know how to deep copy
    • know what kinds of classes need to be copy constructed
      • only mutable classes need a copy constructor
  • Understand how to make methods from scratch, such as equals() and toString()
  • aside from that , just study what goes in a constructor
    • and how to test it.

Monday, January 29, 2007

LabTest 1 Impressions

Here you can post how you felt the test went, give pointers to those who haven't taken it and so on.

  • We asked Andrew about test specifications
    • he said 'In the book, so far we have done chapters 3 and 9, and a little bit of chapter 13.'
    • he also said the best way to study for it is lecture notes, as there is material he skipped that we shouldn't have to be tested on
    • he said the Lab Tests will commonly be
      • editing sample code that doesn't work
      • make a class w/ a given API
      • make a class of your own that meets specs (similar to what we've done in lab1 / lab2

Off topic from the test...

how do you guys feel about the lab TA's?
I want Maan back, I can never really get much coherent help.. but if you guys know a good TA i should be talking to .. post their name on here for me.

  • Andrew posted this on his site about test:

Lecture 11

Inheritance

  • say we are implementing a database of students in a course
    • course is open to both undergraduate and graduate students
    • obviously, the student records will be largely the same
  • All students have
    • Name
    • Student Number
    • Raw Percentage Score
  • calculation of the letter grade is different between these students
  • Undergrad
    • A 80-100%
    • B 70-80%
    • C 60-70%
    • D 50-60%
    • F <50%
  • Graduate Student
    • A 80-100%
    • B 70-80%
    • F <70%
  • inefficient to implement two separate classes when they overlap so much
  • intuitively, both an undergrad and grad are types of students with certain features in common. it would be nice if student class could handle common functions and that this class could be extended
  • Java allows us to extend this way using inheritance
    • use the 'extends' keyword to declare child classes
public class Student
{
//parent class
//takes care of common features
//student name / number / raw score
}

____________________________________

public class underGradStudent extends Student
{
//undergrad letter grade calculation
}


____________________________________

public class gradStudent extends Student
{

//grad letter grade calculation
}

_____________________________________

Inheritance and Constructors

  • if you provide no constructor in a child class that will lead the compiler to call the default constructor of the parent and will generate an error if that doesn't exist.
  • provide a constructor
    • presumably you went to call the constructor of the parent class
  • use the keyword 'super' (works like keyword 'this')
Access Specifiers

  • private members are hidden from children
  • this is sometimes valuable to have internal hidden variables that can't be manipulated outside your class
  • protected objects are visible to children but not the public
Package and Access Restrictions
  • four valid access specifiers
    • private
      • most restricted
      • class file only
    • nothing
      • access within package
    • protected
      • access within package and children
    • public
      • accessible everywhere
  • ignore packages
    • and java puts all files in the same package
  • package
    • package level access throughout the code
Creating and Using Package

  1. Create a package
    1. think of a name for package
      1. all lower case letters
    2. create a directory with that name
      1. move all files to that directory
    3. in all files in student write the following statement as the first line
      1. package student;
    4. using the package
      1. at the top you write the following
        1. import student.*;

Saturday, January 27, 2007

Lecture 10

  • Delegation within the class definition
    • code is sometimes used over and over within the methods of a class
    • constructors =>implement the constructor that takes all possible arguements and call that constructor from the other constructors.
  • why do this?
    • saves you time
    • making changes is much easier, and less error prore(eg. you might miss a change.)
  • Constructor Fields(final keyword)
    • best practice to use a variable to store any constants used by your program
    • want these values to be protected from change
  • public final int CONSTANTS = s;
    • constant is initially given the value s
    • no entity in the program is allowed to alter constant
    • final entities must be initialized on the same line that they are declared
    • stylistically, final variables are always written in all caps.
  • why use constants?

Example.
private int x
private final int MAX = 500;
...
if (x > MAX - x ) { }
    • -there are other uses of final
  • method class
    • inheritance
  • variable
    • constant
  • The constant feature only works with primitives
  • if you declare an object final, that object does not magically become immutable
  • Preconditions and postconditions as the system programmer, you have a contractual relationship with the application programmer.
Precondition:
  • AP calls your methods satisfying conditions which you specify
  • eg. amount >= 0 indeposit(), withdrawal
  • Postcondition:
    • In return, you agree that the method output satisfies given conditions
    • Example: getbalance() returns the correct balance
    • Preconditions dont need to be checked
    • postcondition should be checked during debugging
    • assert checking to ensure postconditions be satisfied
    • pre and postconditions must be specified in javadoc

Wednesday, January 24, 2007

Lecture 9

Special Functions
  • already we have seen clone()
    • this is a special method that is possessed by all objects
  • we will talk about two more in this lecture
    • toString()
    • equals()
ToString()
  • returns an object of type String
  • 'cast' your object object to a string type
  • creates a string output of your objects current state
    • contents of all private instance fields
  • very useful for debugging
  • the compiler uses toString() whenever it needs to cast your object to a String
Example

MyObject x = new MyObject();
System.out.println(x);


  • println takes a String argument
  • this is equivalent to saying:
  • System.out.println(x.toString());
  • In a toString method you should do the following
    • include the name of the class
    • include all the private fields
Example
  • if MyObject contains only a private int a
    • toString() output should be
      • MyObject[a=0]
Equals()
  • returns a boolean
    • true or false
  • checks to see whether two objects are equal
  • returns true if they are equal, false if they are not
The default form of this method is

Public boolean equals(Object, OtherObject)

  • we must use the most general form of the default equals() in order to capture all objects
Public Class MyObject{

private int x;
public boolean equals(Object, OtherObject){
MyObject other = (MyObject)OtherObject;
return (this.x == other.x);

  • if x and y are objects and not primitives then
    • x==y if x and y point to the same object
Delegation within the class
  • Example: code used by many methods in the same class
  • Example: Constructors

Monday, January 22, 2007

Lab 2

Please Post your ideas for Lab 2 here! I haven't started yet, my labs are on tuesday!

For Lab Instructions: Click

Lecture 8

Scope of Variables

  • how far are the declared variables visible in code?
  • when is it safe to refuse variable names?
  1. Local variables within a method
    1. always applies to the method parameters
    2. the scope of local variables is the set of {} that contains the definition
    3. this is usually, but not always, the braces {} surrounding the entire method
    4. not allowed to have two variables of the same name within the same set of braces{}

Example
public void method(){ int x=o; int x=5; // illegal }

Example 2

public void method(){
x=0 //illegal

if (y==5)
{ int x = 0;
x=x+y;
}
else {
int x = 5;
}


  • x is only accessible through the scope of {} between if and else
  • putting x = 0 at the top is illegal because it is outside the desired scope

2. Local variables vs. Instance Fields


public class BankAccount{
Private double balance;
public void method ()
{
double balance; //legal
balance = 0; // legal - this is legal because local variables take precedence

this.balance = 0; // instance field relates to balance


3. Multiple Objects

  • methods of an object can see private fields of any object of that class

private double balance

public void method(BankAccount x){
balance = 0; //current object
x.balance = 0 // other object

// if user typed x.method(y) then x would relate to
balance = 0 and y would relate to balance = 0

Clone, shallow copies, deep copies
  • implement copy constructors to perform defensive copies which avoids privacy leaks
  • you may be tempted to use the method clone() as an easy copy constructor.
  • the only time to use clone() is if no copy constructor is defined.

example
MOWC a,b;
a = new MOWN();
b=a.clone(); // creates a shallow copy of a and store it in b

// this is similar to but not identical to using the copy constructor

what does clone do?
  • creates a bitwise copy of the object

Example

{ int a,b;
private myobject c;}
// my object is mutable}

//console
x = new MOWC():
//this example would give a reference to myobject c even if copied it will reference the same object instead of a new

  • two references
  • changes y to show up in x
  • privacy leak
  • this is a shallow copy
  • clone() implements a shallow copy, which does not respect the semantics of the object it copies
  • shallow copies can lead to a privacy leak
  • Deep Copy
    • implements a copy constructor

public class MOWC(MOWC in){
a = in.a;
b=in.b;
c= new myobject(in.c);
}
//this is the correct way to deep copy

  • shallow copy is safe if your object contains
    • primitives
    • immutable classes
  • deep copy is mandatory if object contains mutable classes
  • From Now On
    • properly implement a copy constructor for all mutable classes that you design
  • Only
    • use clone() if no copy constructor exists