310 likes | 428 Views
In š tan čné vs. triedne. AClass.classInteger = 7; System.out.println(classMethod()); System.out.println(anInstance.classMethod()); anInstance.classInteger = 9; System.out.println(anInstance.classMethod()); System.out.println(
E N D
Inštančnévs.triedne AClass.classInteger = 7; System.out.println(classMethod()); System.out.println(anInstance.classMethod()); anInstance.classInteger = 9; System.out.println(anInstance.classMethod()); System.out.println( anotherInstance.classMethod()); } } 1 2 7 7 9 9 public class AClass { public int instanceInteger = 0; public int instanceMethod() { return instanceInteger; } public static int classInteger = 0; public static int classMethod() { return classInteger; } public static void main(String[] args) { AClass anInstance = new AClass(); AClass anotherInstance = new AClass(); anInstance.instanceInteger = 1; anotherInstance.instanceInteger = 2; System.out.println( anInstance.instanceMethod()); System.out.println( anotherInstance.instanceMethod()); //System.out.println(instanceMethod()); //System.out.println(instanceInteger);
Konvencie • 80% životného cyklu software spotrebuje jeho údržba, • málokedy je software celý cyklus udržiavaný jedným programátorom, autorom... • konvencie kódovania majú uľahčiť čitateľnosť kódu iným, či aj mne po rokoch preto: http://java.sun.com/docs/codeconv/html/CodeConvTOC.doc.html Triedy,napr.: class Raster; class ImageSprite; Meno triedy je podstatné meno, každé podslovo začína veľkým písmenkom (mixed case), celé meno začína veľkým písmenom. Meno je jednoduché a dobre popisujúce. Metódy, napr.: run();runFast();getBackground(); Mená metód sú slovesá, začínajú malým písmenom. Premenné, napr. int i; char c; float myWidth; Začínajú malým písmenom, mixed case, nezačínajú _ resp. $ Jednopísmenkové mená sú na dočasné premenné. Konštanty, napr. static final int MIN_WIDTH = 4; static final int MAX_WIDTH = 999; static final int GET_THE_CPU = 1; Veľkými, slová oddelené ("_").
Dedičnosť • class A extends B ... • pridanie novej funkcionality (premenných a metód) • predefinovanie existujúcich funkcií predka (override) • vzťah is-a vs. is-like-a • dynamic binding = polymofizmus void doStuff(Shape s) { s.erase(); // ... s.draw(); } Circle c = new Circle(); Triangle t = new Triangle(); Line l = new Line(); doStuff(c); doStuff(t); doStuff(l);
this public class HSBColor { private int hue, saturation, brightness; public HSBColor (int hue, int saturation, int brightness) { this.hue = hue; this.saturation = saturation; this.brightness = brightness; } } public class Rectangle { private int x, y; private int width, height; public Rectangle() { this(0, 0, 0, 0); } public Rectangle(int width, int height) { this(0, 0, width, height); } public Rectangle(int x, int y, int width, int height) { this.x = x; this.y = y; this.width = width; this.height = height; } ... }
super public class Superclass { public boolean aVariable; public void aMethod() { aVariable = true; } } public class Subclass extends Superclass { public boolean aVariable; //overrides aVariable in Superclass public void aMethod() { //overrides aMethod in Superclass aVariable = false; super.aMethod(); System.out.println(aVariable); System.out.println(super.aVariable); } } false true
Konštruktor nadtriedy class A { A() { System.out.println("A constructor"); } } class B extends A { B() { System.out.println("B constructor"); } } public class C extends B { C() { System.out.println("C constructor"); } public static void main(String[] args) { C x = new C(); } } A constructor B constructor C constructor
Konštruktor nadtriedy class A { A(int i) { System.out.println("A constructor"); } } class B extends A { B(int i) { super(i); System.out.println("B constructor"); } } public class C extends B { C() { super(11); System.out.println("C constructor"); } public static void main(String[] args) { C x = new C(); } } A constructor B constructor C constructor
Kompozícia class E { E(int i) { System.out.println("E constructor"); } } public class F extends E { C c; // kompozícia objektov D d; A a; F(int i) { super(i + 1); c = new C(i + 2); d = new D(i + 3); a = new A(i + 5); System.out.println("F constructor"); } public static void main(String[] args) { F f = new F(9); } } class A { A(int i) { System.out.println("A constructor"); } } class B { B(int i) { System.out.println("B constructor"); } } class C extends B { C(int i) { super(i); System.out.println("C constructor"); } } class D extends B { D(int i) { super(i); System.out.println("D constructor"); } } E,B,C,B,D,A,F
Metódy abstract abstract class GraphicObject { int x, y; ... void moveTo(int newX, int newY) { ... } abstract void draw(); } class Circle extends GraphicObject { void draw() { ... } } class Rectangle extends GraphicObject { void draw() { ... } }
Triedy a metódy final neexistuje inštancia, resp. nemožno overridovať, dôvody, napr.: • bezpečnosť, ... • softwarový návrh, ... final class ChessAlgorithm { ... } class ChessAlgorithm { ... final void nextMove(CPiece pieceMoved,BoardLocation newLocation) { ... } ... }
Moj prvy Stack class Main { public static void main(String[] args) { final int SSIZE = 100; Stack s = new Stack(SSIZE); for(int i=0; i<SSIZE; i++) s.push(i); while (!(s.isEmpty())) { System.out.println(s.pop()); } } } public class Stack { protected int[] S; // reprezentácia protected int top = -1; public Stack(int Size) { S = new int[Size]; } public int size() { return (top + 1); } public boolean isEmpty() { return (top < 0); } public void push(int element) { if (size() == S.length)System.out.println("Stack is full."); S[++top] = element; } public int pop() { int element; if (isEmpty()) { System.out.println("Stack is empty."); return -1; } element = S[top--]; return element; } }
Stack ++ import java.util.Stack; ……. Stack pd = new Stack(); pd.push(new Integer(123456)); pd.push("ahoj"); String s = (String)pd.pop(); Integer numb = (Integer)pd.pop(); public void push (Object item) { if (top == S.length) { Object[] newS = new Object[S.length * 2]; for (int i=0; i<S.length; i++) { newS[i] = S[i]; } S = newS; } public class Stack { protected Object[] S; protected int top; public Stack (int Size) { this.S = new Object[Size]; this.top = 0; } public boolean isEmpty () { return top == 0; } public void push (Object item) { S[top] = item; top++; } public Object pop () { top--; return S[top]; } }
Stack – templates (v.5.0) public class Stack<E> { protected E[] S; protected int top; public Stack (int Size) { S = (E[]) new Object[Size]; top = 0; } public boolean isEmpty () { return top == 0; } public void push (E item) { S[top] = item; top++; } public E pop () { top--; return S[top]; } } Stack<String> st = new Stack<String>(); st.push("caf"); String s = st.pop();
Parent [(()())[()]] public void checkParent(String input) { int stackSize = input.length(); Stack theStack = new Stack(stackSize); for (int j = 0; j < input.length(); j++) { char ch = input.charAt(j); switch (ch) { case '[': case '(': theStack.push(ch); break; case ']': case ')': if (!theStack.isEmpty()) { char chx = theStack.pop(); if ((ch == ']' && chx != '[') || (ch == ')' && chx != '(')) return false; } else return false; break; } } return (theStack.isEmpty()); }
Stack - interface publicclassEmptyStackException extendsRuntimeException { public EmptyStackException(String err) { super(err); } } publicclassFullStackException extendsRuntimeException { public FullStackException(String err) { super(err); } } publicinterfaceStack<E> { public intsize(); public booleanisEmpty(); public E top() throwsEmptyStackException; public voidpush (E element) throwsFullStackException; public E pop() throwsEmptyStackException; }
Stack – implementation publicclassArrayStack<E> implementsStack<E> { protected int capacity; protected E S[]; protected int top = -1; public ArrayStack() { this(1000); } public ArrayStack(int cap) { capacity = cap; S =(E[]) newObject[capacity]; } .... public voidpush(E element) throwsFullStackException { if(size() == capacity) thrownewFullStackException("Stack is full."); S[++top] = element; } public E top() throwsEmptyStackException { if(isEmpty()) thrownewEmptyStackException("Stack is empty."); returnS[top]; }
Stack - main public E pop() throwsEmptyStackException { E element; if(isEmpty()) thrownewEmptyStackException("Stack is empty."); element = S[top]; S[top--] = null; // dereference S[top] for garbage collection. returnelement; } public StringtoString() { String s; s = "["; if(size() > 0) s+= S[0]; if(size() > 1) for(int i = 1; i <= size()-1; i++) s += ", " + S[i]; returns + "]"; } public staticvoid main(String[] args) { ArrayStack<String> B = newArrayStack<String>(); B.push("Bob"); B.push("Alice"); Object o = B.pop(); B.push("Eve"); } }
Java Collections • interface • implementation • algorithm
Interface public interface Collection<E> extends Iterable<E> { int size(); boolean isEmpty(); boolean contains(Object element); boolean add(E element); //optional boolean remove(Object element); //optional Iterator<E> iterator(); …. Object[] toArray(); <T> T[] toArray(T[] a); }
Iterator public interface Iterator<E> { boolean hasNext(); E next(); void remove(); //optional } static void filter(Collection<?> c) { for (Iterator<?> it = c.iterator(); it.hasNext(); ) if (!cond(it.next())) it.remove(); } for (Object o : collection) System.out.println(o);
Implementations Hash Table Resizable Array Balanced Tree Linked List Interface Collection HashSet ArrayList TreeSet LinkedList Set HashSet TreeSet SortedSet TreeSet List ArrayList LinkedList Map HashMap TreeMap SortedMap TreeMap Implementation
Interface vs. Implementation • ArrayList nemusí byť prealokovaný pri náraste • LinkedList a ArrayList možno použiť ako FIFO (list.add() / list.remove(0)) • TreeMap a TreeSet sú usporiadané, potrebujú porovnanie • Set a Map nemôžu obsahovať duplikáty • Map obsahuje páry (key;object) prístupné cez kľúč key • Prvky môžu byť indexované • Prvky možeme prechádzať sekvenčne • Najčastejšia implementácia • Set interface ako HashSet • List interface ako ArrayList • Map interface ako HashMap • Queue interface ako LinkedList
public interface Set<E> extends Collection<E> { int size(); boolean isEmpty(); boolean contains(Object element); boolean add(E element); //optional boolean remove(Object element); //optional Iterator<E> iterator(); // Array Operations Object[] toArray(); <T> T[] toArray(T[] a); } Set/HashSet import java.util.*; public class FindDuplicates { public static void main(String[] args) { Set<String> s = new HashSet<String>(); for (String a : args) if (!s.add(a)) System.out.println("Duplicate: " + a); System.out.println(s.size() + " distinct words: " + s); } } java FindDups i came i saw i left Duplicate : i Duplicate : i 4 distinct words: [i, left, saw, came]
public interface SortedSet<E> extends Set<E> { SortedSet<E> subSet(E fromElement, E toElement); SortedSet<E> headSet(E toElement); SortedSet<E> tailSet(E fromElement); // Endpoints E first(); E last(); // Comparator access Comparator<? super E> comparator(); } SortedSet/TreeSet import java.util.Arrays; import java.util.Iterator; import java.util.SortedSet; import java.util.TreeSet; SortedSet sortedSet = new TreeSet(Arrays.asList( "one two three four five six seven eight".split(" "))); System.out.println(sortedSet);// eight, five, four, one, seven, six, three, two Object low = sortedSet.first(), high = sortedSet.last(); // eight, two Iterator it = sortedSet.iterator(); for (int i = 0; i <= 6; i++) { if (i == 3) low = it.next(); // one if (i == 6) high = it.next(); // two else it.next(); } System.out.println(sortedSet.subSet(low, high)); // one, seven, six, three System.out.println(sortedSet.headSet(high)); // eight, five, four, one, seven, six, three System.out.println(sortedSet.tailSet(low)); // one, seven, six, three, two
List/ArrayList import java.util.*; a b c d d foo a public class ListDemo { public static void main(String[] args) { String[] p = {"a","b","c","d"}; List <String> s = new ArrayList<String>(); for (String a : p) s.add(a); for (Iterator it = s.iterator();it.hasNext(); ) System.out.println(it.next()); s.set(1,"foo"); s.remove(2); for (ListIterator<String> it = s.listIterator(s.size());it.hasPrevious(); ) System.out.println(it.previous()); } }
List public interface List<E> extends Collection<E> { // Positional access E get(int index); E set(int index, E element); boolean add(E element); void add(int index, E element); E remove(int index); boolean addAll(int index, Collection<? extends E> c); // Search int indexOf(Object o); int lastIndexOf(Object o); // Iteration ListIterator<E> listIterator(); ListIterator<E> listIterator(int index); // Range-view List<E> subList(int from, int to); }
Map/HashMap import java.util.*; public class Freq { public static void main(String[] args) { Map<String, Integer> m = new HashMap<String, Integer>(); for (String a : args) { Integer freq = m.get(a); m.put(a, (freq == null) ? 1 : freq + 1); } System.out.println(m); } } java Freq if it is to be it is up to me to delegate {to=3, delegate=1, be=1, it=2, up=1, if=1, me=1, is=2}
Ordered import java.util.*; public class NameSort { public static void main(String[] args) { Name nameArray[] = { new Name("John", "Lennon"), new Name("Karl", "Marx"), new Name("Groucho", "Marx"), new Name("Oscar", "Grouch") }; List<Name> names = Arrays.asList(nameArray); Collections.sort(names); System.out.println(names); } }
Comparable public class Name implements Comparable<Name> { private final String firstName, lastName; public Name(String firstName, String lastName) { ... } public String firstName() { ... } public String lastName() { ... } public String toString() { ... } public boolean equals(Object o) { if (!(o instanceof Name)) return false; Name n = (Name)o; return n.firstName.equals(firstName) && n.lastName.equals(lastName); } public int compareTo(Name n) { int lastCmp = lastName.compareTo(n.lastName); return (lastCmp != 0 ? lastCmp : firstName.compareTo(n.firstName)); } }
Vnorené triedy class EnclosingClass { ... static classStaticNestedClass { ... } class InnerClass { ... } } class EnclosingClass { ... class ANestedClass { ... } }
Vnorené triedy anonymné public class Stack { private Object[] items; public Iterator iterator() { return new Iterator() { int currentItem = items.size() - 1; public boolean hasNext() { ... } public Object next() { ... } public void remove() { ... } } } } public class Stack { private Object[] items; public Iterator iterator() { return new StackIterator(); } class StackIterator implements Iterator { int currentItem = items.size() - 1; public boolean hasNext() { ... } public Object next() { ... } public void remove() { ... } } }