in š tan čné vs. triedne

31
Inštančné vs. triedne 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); AClass.classInteger = 7; System.out.println(classMethod()); System.out.println(anInstance.classMet hod()); anInstance.classInteger = 9; System.out.println(anInstance.classMet hod()); System.out.println( anotherInstance.classMethod()); } } 1 2 7 7 9 9

Upload: verne

Post on 05-Jan-2016

32 views

Category:

Documents


0 download

DESCRIPTION

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( - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: In š tan čné vs. triedne

Inštančné vs. triednepublic 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);

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()); }}127799

Page 2: In š tan čné vs. triedne

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é ("_").

Page 3: In š tan čné vs. triedne

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);

Page 4: In š tan čné vs. triedne

thispublic 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; } ...}

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; }}

Page 5: In š tan čné vs. triedne

superpublic 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

Page 6: In š tan čné vs. triedne

Konštruktor nadtriedyclass 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 constructorB constructorC constructor

Page 7: In š tan čné vs. triedne

Konštruktor nadtriedyclass 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 constructorB constructorC constructor

Page 8: In š tan čné vs. triedne

Kompozíciaclass 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");

}

}

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); }}

E,B,C,B,D,A,F

Page 9: In š tan čné vs. triedne

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() { ... }}

Page 10: In š tan čné vs. triedne

Triedy a metódy finalneexistuje 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) { ... } ...}

Page 11: In š tan čné vs. triedne

Moj prvy Stackpublic 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; } }

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()); } }}

Page 12: In š tan čné vs. triedne

Stack ++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]; }}

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;}

Page 13: In š tan čné vs. triedne

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();

Page 14: In š tan čné vs. triedne

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()); }

Page 15: In š tan čné vs. triedne

Stack - interfacepublic class EmptyStackException extends RuntimeException { public EmptyStackException(String err) { super(err); }}

public class FullStackException extends RuntimeException { public FullStackException(String err) { super(err); }}

public interface Stack<E> { public int size(); public boolean isEmpty(); public E top() throws EmptyStackException; public void push (E element) throws FullStackException; public E pop() throws EmptyStackException; }

Page 16: In š tan čné vs. triedne

public class ArrayStack<E> implements Stack<E> { protected int capacity; protected E S[]; protected int top = -1;

public ArrayStack() { this(1000); } public ArrayStack(int cap) { capacity = cap; S = (E[]) new Object[capacity]; } .... public void push(E element) throws FullStackException { if (size() == capacity) throw new FullStackException("Stack is full."); S[++top] = element; } public E top() throws EmptyStackException { if (isEmpty()) throw new EmptyStackException("Stack is empty."); return S[top]; }

Stack – implementation

Page 17: In š tan čné vs. triedne

Stack - mainpublic E pop() throws EmptyStackException { E element; if (isEmpty()) throw new EmptyStackException("Stack is empty."); element = S[top]; S[top--] = null; // dereference S[top] for garbage collection. return element; } public String toString() { String s; s = "["; if (size() > 0) s+= S[0]; if (size() > 1) for (int i = 1; i <= size()-1; i++) s += ", " + S[i]; return s + "]"; } public static void main(String[] args) { ArrayStack<String> B = new ArrayStack<String>(); B.push("Bob"); B.push("Alice"); Object o = B.pop(); B.push("Eve"); }}

Page 18: In š tan čné vs. triedne

Java Collections

• interface• implementation• algorithm

Page 19: In š tan čné vs. triedne

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);

}

Page 20: In š tan čné vs. triedne

Iteratorpublic 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);

Page 21: In š tan čné vs. triedne

Implementation

       

Implementations

Hash Table

Resizable Array Balanced Tree Linked List

Interface

CollectionHashSet

ArrayList TreeSet LinkedList

SetHashSet

TreeSet

SortedSet TreeSet

List ArrayList LinkedList

MapHashMap

TreeMap

SortedMap TreeMap

Page 22: In š tan čné vs. triedne

Interface vs. Implementation

1. ArrayList nemusí byť prealokovaný pri náraste2. LinkedList a ArrayList možno použiť ako FIFO (list.add() /

list.remove(0)) 3. TreeMap a TreeSet sú usporiadané, potrebujú porovnanie4. Set a Map nemôžu obsahovať duplikáty5. Map obsahuje páry (key;object) prístupné cez kľúč key6. Prvky môžu byť indexované7. Prvky možeme prechádzať sekvenčne

Najčastejšia implementácia1. Set interface ako HashSet2. List interface ako ArrayList3. Map interface ako HashMap4. Queue interface ako LinkedList

Page 23: In š tan čné vs. triedne

Set/HashSet

 

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 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);}

import java.util.*;

Page 24: In š tan čné vs. triedne

SortedSet/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

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();}

import java.util.Arrays;import java.util.Iterator;import java.util.SortedSet;import java.util.TreeSet;

Page 25: In š tan čné vs. triedne

List/ArrayListpublic 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()); }}

a

b

c

d

d

foo

a

import java.util.*;

Page 26: In š tan čné vs. triedne

Listpublic 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);}

Page 27: In š tan čné vs. triedne

Map/HashMap

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}

import java.util.*;

Page 28: In š tan čné vs. triedne

Orderedpublic 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);

}

}

import java.util.*;

Page 29: In š tan čné vs. triedne

Comparablepublic 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)); }}

Page 30: In š tan čné vs. triedne

Vnorené triedyclass EnclosingClass {

...

class ANestedClass {

...

}

}

class EnclosingClass {

...

static class StaticNestedClass {

...

}

class InnerClass {

...

}

}

Page 31: In š tan čné vs. triedne

Vnorené triedy anonymné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() { ... } }}

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() {

...

}

}

}

}