9 2
9 2
9 2
A pen has a or
contains a ball
Has-a Relationships
Has-a relationship
Abstract Classes
Example
Abstract Classes
Abstract Classes
Abstract classes
Abstract Classes
Generic programming
Generic programming
example
solution: use templates
Example: (implementation of Stack with linked list)
public class Node <T> {
private T item;
private Node<T> next;
Generic programming
example
public void setItem(T newItem) {
item = newItem;
} // end setItem
public T getItem() {
return item;
} // end getItem
public void setNext(Node<T> nextNode) {
next = nextNode;
} // end setNext
public Node<T> getNext() {
return next;
} // end getNext
} // end class Node
Generic Stack
public class StackReferenceBased <T> {
private Node<T> top;
public StackReferenceBased() {
top = null;
} // end default constructor
public boolean isEmpty() {
return top == null;
} // end isEmpty
public void push(T newItem) {
top = new Node<T>(newItem, top);
} // end push
public T pop() throws StackException {
if (!isEmpty()) {
Node<T> temp = top;
top = top.getNext();
return temp.getItem();
}
else {
throw new StackException("StackException on " +
"pop: stack empty");
} // end if
} // end pop
how to use:
etc..