PiKKS
Ukratko Općenito Osnovni elementi OOP u Javi Overloading, overriding, virtual method invocation, modifikatori... Exceptions Java GUI Threads
Predavanje za godina prvog ciklusa Poznavanje programskog jezika C++ Poznavanje OOP kroz C++ Ambiciozna generacija...
Good choice
Java Object oriented Distributed Simple Multithreaded Secure Platform idependent JVM
Deklaracija i inicijalizacija [modifiers] type identifier [=value]; private int myInt=10; char karakter = ‘G’; public bool test = (myInt <20); int[] niz; char niz[] = new char[10];
Kontrola toka 1/2 if (Uslov) { Naredbe; } else { Naredbe; } == >= <
Kotrola toka 2/2 switch (variabla) { case vrijednost1: naredbe; [break;] case vrijednost2:... [default:]... } variabla može biti samo tipa char, byte, short ili int
Petlje 1/3 while (uslov) { Naredbe; }
Petlje 2/3 do { Naredbe; } while (uslov);
Petlje 3/3 for (incijalizacija [,inicijalizacija]; uslov; azuriranje [,azuriranje]) { Naredbe; }
Klasa public class NazivKlase{ Metode; public static void main(String args[]){... }
Struktura jednog file-a.java [package_deklaracije] [import_statements] + package shipping.reports; import shipping.domain.*; import java.util.List; import java.io.*; public class VehicleCapacityReport{...
Metode [modifikatori] povratniTip nazivMetode ([argumenti]){ Naredbe; } public static void main (String args[]) { Naredbe; }
Konstruktor [modifikatori] NazivKlase ([argumenti]){ Naredbe; } Default konstruktor
Objekat NazivKlase nazivObjekta = new NazivKlase(); nazivObjekta.setTezina(75); Pristup
int counter = 10; NekaMajica obj1 = new NekaMajica(’U’); NekaMajica obj2 = new NekaMajica(’B’); 10 0x x45F U 0 B StackHeap counter obj1 obj2
obj1 = obj2; 10 0x45F U 0 B StackHeap counter obj1 obj2 X
Enkapsulacija Sakriva implementacione detalj Forisira koirštenje interface-a klase za prisutp Čini kod lakšim za održavanje this referenca
Naslje đ ivanje single inheritance model class NazivKlase extends RoditeljKlasa interface-i daju mogućnost višestrukog naslje đ ivanja (poslije) super referenca Object, praklasa svih klasa
Modifikatori pristupa 1/3 + public # protected - private default + metoda1 # metoda2 metoda3 - metoda4 + metoda1 # metoda2 metoda3 - metoda4 Klasa koja se nalazi u istom paketu kao klasa Test Test.java
Modifikatori pristupa 2/3 + public # protected - private default + metoda1 # metoda2 metoda3 - metoda4 + metoda1 # metoda2 metoda3 - metoda4 Klasa naslje đ uje (extenda) klasu Test Test.java
Modifikatori pristupa 3/3 + public # protected - private default + metoda1 # metoda2 metoda3 - metoda4 + metoda1 # metoda2 metoda3 - metoda4 Bilo koja klasa koja importuje paket u kojem je klasa Test Test.java
Overriding Klasa koja naslje đ uje neku drugu klasu može modifikovati ”ponašanje” metode iz klase roditelj Ono što mora ostati isto kao u roditeljskoj klasi: naziv tip povratne vrijednosti lista argumenata Metoda u klasi dijete ne smije imati restriktivniji modifikator pristupa Exception-i ne smiju biti generalniji
Polimorfizam 1/2 mogućnost da jedna metoda obavlja različite funkcije u zavisnosti od objekat u uskoj je vezi sa naslje đ ivanjem overriding i overloading su dva tipa polimorfizma
Polimorfizam 2/2 Roditelj klasa Animal Dijete klase Dog i Cat Animal pas = new Dog(“Woofy”); Animal maca = new Cat (“Fluffy”);
Virtual method invocation 1/2 ili dynamic method binding Animal pas = new Dog(“Woofy”); Animal maca = new Cat(“Fluffy”); pas.makeSound(); maca.makeSound();
Virtual method invocation 2/2 referenca tipa KlasaRod KlasaDijete +metoda1 +metoda4 +metoda5 +metoda2 +metoda3 KlasaDijete +metoda1 +metoda4 +metoda5 +metoda2 +metoda3 KlasaRod +metoda1 +metoda2 +metoda3 KlasaRod +metoda1 +metoda2 +metoda3 Object Objekat koji je instanciran je tipa KlasaDijete metoda1 je overriden
Casting instanceof služi za testiranje tipa objekta služi da bismo dobili punu funkcionalnost objekta cust up implicitno cust down explicitno Dog cuko = (Dog)pas;
Overloading Lista argumenata mora biti različita Povratni tip može biti drugačiji Ime je isto Overloading konstruktora
Konstruktori Konstruktori se ne naslje đ uju Rješenje: koristiti default konstruktor napisati eksplicitan konstruktor super referencom pozivamo roditeljske konstruktore poziv roditeljskog konstruktora je prva linija ako nema explicitnog poziva poziva se super()
Wrapper klase Java primitivne tipove ne posmatra kao objekte Wrapper klase služe da primitivne tipove posmatramo kao objekte Objekti su immutable
static static je modifikator koji se koristi na varijablama, metodama i ugniježdenim klasama static asocira atribut ili metodu sa klasom, a ne sa konkretnom instancom static members se nazivaju class members, odnosno class attributes ili class methods
final final označava klase koje se ne mogu dalje naslje đ ivati final označava metode koje se ne mogu override-ati final varijable su konstante
abstract abstract označava klase koje se ne mogu instancirati abstract označava metode koje se moraju override-ati
Interfaces 1/2 is contract between client code and the class that implements that interface niti jedna metoda nema implementaciju više nepovezanih klasa može implementirati interface jedna klasa može implementirati više interface-a referenca može biti tipa interface-a
Interfaces 2/2 referenca tipa interface-a IDemo KlasaDijete +metoda1 +metoda4 +metoda5 +metoda2 +metoda3 KlasaDijete +metoda1 +metoda4 +metoda5 +metoda2 +metoda3 KlasaRod +metoda1 +metoda2 +metoda3 KlasaRod +metoda1 +metoda2 +metoda3 Object Objekat koji je instanciran je tipa KlasaDijete metoda1 je overriden + metoda6 +metoda7
Exceptions Checked compile-time exceptions Unchecked run-time exceptions errors API prikazuje listu checked exception-a
Exception handling try catch... finally ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, SecurityException...
The handle or declare rule Handle exception koristeći try-catch-finally Deklariši da kod baca exception koristeći throws Naravno nema potrebe za handle-anjem ili deklarisanjem runtime exception-a i error-a
AWT Components Button Checkbox Label Containers Panel Window ScrollPane
Containers Add components with the add() method. The two main types of containers are Window and Panel. A Window is a free floating window on the display. A Panel is a container of GUI components that must exist in the context of some other container, such as a window or applet.
Pozcioniranje komponenti The position and size of a component in a container is determined by a layout manager. You can control the size or position of components by disabling the layout manager. You must then use setLocation(), setSize(), or setBounds() on components to locate them in the container.
Paneli Panels provide a space for components. This enables subpanels to have their own layout manager.
Layout managers FlowLayout BorderLayout GridLayout CardLayout GridBagLayout
Default layout managers
FlowLayout Adds components from left to right, top to bottom Alignment default is centered Uses components preferred sizes
FlowExample 1 import java.awt.*; 2 3 public class FlowExample { 4 private Frame f; 5 private Button button1; 6 private Button button2; 7 private Button button3; 8 9 public FlowExample() { 10 f = new Frame("Flow Layout"); 11 button1 = new Button("Ok"); 12 button2 = new Button("Open"); 13 button3 = new Button("Close"); 14 }
FlowExample public void launchFrame() { 17 f.setLayout(new FlowLayout()); 18 f.add(button1); 19f.add(button2); 20 f.add(button3); 21 f.setSize(100,100); 22 f.setVisible(true); 23 } public static void main(String args[]) { 26 FlowExample guiWindow = new FlowExample(); 27 guiWindow.launchFrame(); 28 } 29 }
BorderLayout Components are added to specific regions The resizing behavior is as follows: North, South, and Center regions adjust horizontally East, West, and Center regions adjust vertically
Organizacija broder layout-a
BorderExample f.add(bn, BorderLayout.NORTH); f.add(bs, BorderLayout.SOUTH); f.add(bw, BorderLayout.WEST); f.add(be, BorderLayout.EAST); f.add(bc, BorderLayout.CENTER);
GridLayout Components are added from left to right, and from top to bottom. All regions are sized equally. The constructor specifies the rows and columns. f.setLayout (new GridLayout(3,2));
Šta je event? Events – Objects that describe what happened Event sources – The generator of an event Event handlers – A method that receives an event object, deciphers it, and processes the user’s interaction An event can be sent to many event handlers Event handlers register with components when they are interested in events generated by that component
Listener Example public void launchFrame() { b.addActionListener(new ButtonHandler()); f.add(b,BorderLayout.CENTER); f.pack(); f.setVisible(true); } public class ButtonHandler implements ActionListener { public void actionPerformed(ActionEvent e) { System.out.println("Action occurred");...
Kategorije event-a
Thread-ovi Thread of execution results from a fork of a computer program into two or more concurrently running tasks Thread is contained inside a process The three parts of at thread are: CPU Code Data Threads share the same data and code
Kreiranje thread-a public class ThreadTester { public static void main(String args[]) { HelloRunner r = new HelloRunner(); Thread t = new Thread(r); t.start();} class HelloRunner implements Runnable { int i; public void run() { i = 0; while (true) { System.out.println("Hello " + i++); if ( i == 50 ) { break; }}}}
Thread scheduling
Načini implementacije Implement Runnable: Better object-oriented design Single inheritance Consistency Extend Thread: Simpler code
synchronized Every object has a flag that is a type of lock flag. The synchronized enables interaction with the lock flag. All access to delicate data should be synchronized. Released when the thread passes the end of the synchronized code block Released automatically when a break, return, or exception is thrown by the synchronized code block
Sljedeće je isto public void push(char c) { synchronized(this) { // The push method code }} public synchronized void push(char c) { // The push method code }
State diagram with sychronization
Thread Interaction – wait and notify Scenario: Consider yourself and a cab driver as two threads. The problem: How do you determine when you are at your destination? The solution: You notify the cab driver of your destination and relax. The driver drives and notifies you upon arrival at your destination.
wait and notify the wait() method causes a thread to release the lock it is holding on an object; allowing another thread to run we can specify timeout period for wait when wait() is called, the thread becomes disabled for scheduling and lies dormant until one of four things occur:
Four things: another thread invokes the notify() method for this object and the scheduler arbitrarily chooses to run the thread another thread invokes the notifyAll() method for this object another thread interrupts this thread the specified wait() time elapses
State diagram with wait and notify
Monitor model for sync. Leave shared data in a consistent state. Ensure programs cannot deadlock. Do not put threads expecting different notifications in the same wait pool.
SyncStack example Demo
Literatura many Internet sites Sun materijali za SCJAD i SCJPD