Advertisement
Guest User

Untitled

a guest
Apr 19th, 2018
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 45.92 KB | None | 0 0
  1. Java design patterns:
  2.  
  3. 3 druhy:
  4.  
  5. Where Creational patterns mostly describe a moment of time (the instant of creation), and Structural patterns describe a more or less static structure, Behavioral patterns describe a process or a flow
  6.  
  7. Creational - riešia problémy s vytváraním objektov v systéme a postup vyberu/vytvorenia triedn nového objektu a zabezpečujú ich správny počet. Dejú sa zväčša za behu programu.
  8.  
  9. Abstract Factory - rozhranie pre vytváranie inštancie viacerých rodín objektov
  10. - podobné ako Factory ale všetko je encapsulated a všetko je abstraktne, iba konečný produkt/objekt vie o sebe
  11. - Client/Main, AbstractFactory (interface s createProductA/B metodami), ConcreteFactory1/2 implementuje AbstractFactory
  12. - AbstractProductA/B (interfaci s metódami pre produkty) a ProduktA1/2 & Produkt B1/2 implementujú AbstractProductA/B
  13.  
  14. Builder - oddeluje tvorbu objektov aby sme proces tvorby bol použitelný aj inými inštanciami
  15. - ked chceme vybuildit object z viacerych inych objektov a schovat tvorba objektov z ktorych je vysledny objekt vystavany
  16. - Client/Main, Directory (construct(), metoda ktora dava product dokopy pomocou createProduct()), Builder (interface ktory má createProduct() na vystavania objektu)
  17. - ConcreteBuilder1/2/... (implementuje Builder, vytvara novy product v constructore - private Product product = new Product();, a vracia dany Product cez getter)
  18. - Product (classa ktora obsahuje gettery a settery pre nastavovanie parametrov daneho produktu)
  19.  
  20. Factory Method - rozhranie pre vytváranie objektov a necháva potomkov rozhodnúť aký objekt bude vytvorený
  21. - keď potrebuje aby metóda vytvorila viacero class, ktoré majú rovnakú superclassu počas behu a nevieme koľko nám ich bude treba
  22. - dovoľuje vytvoriť objekty bez toho aby sme špecifikovali presný objekt (špecifikujeme iba Stringom napr.)
  23. - Creator (interface s metodov pre getProduct()), ConcreteCreator (implemetuje Creator interface a obsahuje getter pre getnutie produktu)
  24. - Product1/2/... (obsahuje metódy daného produktu) a ConcreteProduct1/2/... (ktory je dany produkt ktory sme chceli vytvorit)
  25.  
  26. Prototype - nové objekty sú vytvárané kopírovaním/klonovaním prototypu (prvého objektu) ak ich potrebujeme počas runtime-u
  27. - Prototype (interface, ktory implementuje library Cloneable a dalsie metody ktore chceme)
  28. - ConcretePrototype1/2/... (implemetuje Prototype interface aj s clone metodov)
  29.  
  30. @Override
  31. public PrototypeImp clone() throws CloneNotSupportedException{
  32. return (PrototypeImp) super.clone();
  33. }
  34.  
  35. - Client/Main
  36.  
  37. PrototypeImp prototype = new PrototypeImp(1000);
  38. ...
  39. PrototypeImp prototype1 = prototype.clone();
  40.  
  41. Singleton - trieda v ktorej iba jedna inštancia objektu môže existovať (keď nechceme viac ako jednu inštanciu)
  42.  
  43. public class Singleton{
  44.  
  45. private static Singleton instance = null;
  46. private int data;
  47.  
  48. private Singleton(){
  49. data = 0;
  50. }
  51.  
  52. public static getInstance(){
  53.  
  54. if(instance == null){
  55. instance = new Singleton();
  56. }
  57.  
  58. return instance;
  59.  
  60. }
  61.  
  62. public int getData(){
  63. return data;
  64. }
  65.  
  66. public void setData(int data){
  67. this.data = data;
  68. }
  69.  
  70. }
  71.  
  72. public class Main{
  73.  
  74. public static void main(String[] args){
  75.  
  76. Singleton singleton = Singleton.getInstance();
  77. System.out.println(singleton.getData);
  78.  
  79. singleton.setData(10);
  80. System.out.println(singleton.getData);
  81.  
  82. }
  83.  
  84. }
  85.  
  86. ////////////////////////////////////////////////////
  87.  
  88. Structural - zameriavajú sa na usporiadavanie jednotlivých tried/komponentov v systéme, identifikujú vzťahi medzi entitami a definuje ich vzťahy. Sprehľadnujú systém a štruktualizujú kód.
  89.  
  90. Adapter - zabezpečuje spoluprácu dvoch nekompatibelných rozhraní
  91. - Client/Main (vytvárame oba objekty a adapter a adapteru dame 2 nekompatibilný objekt)
  92. - Target (interface ktorý je implementovaný iným objektom/clasov)
  93. - Adapter (classa ktorá implementuje Target interface s jeho metódami a ukladáme doňho referenciu na Adaptee a v implementovaných metódach voláme jeho metódy)
  94.  
  95. EnemyRobot theRobot;
  96.  
  97. public EnemyRobotAdapter(EnemyRobot newRobot){
  98. theRobot = newRobot;
  99. }
  100.  
  101. @Override
  102. public void fireWeapon() {
  103. theRobot.smashWithHands();
  104. }
  105.  
  106. - Adaptee (classa objektu ktorý sme vytvorili aby používal rovnaké metódy aj keď vykonáva svoje vlastné veci)
  107.  
  108. Composite - vytvára stromový systém objektov
  109. - Component (interface v ktorom sú operácie/metódy, ktorý je implementovaný Leafom aj Compositom)
  110. - Composite (obsahuje ArrayList do ktorého vkladáme jednotlivé Leafs)
  111. - Leaf (objekt ktorý má nejaké parametre/metódy a je vkladaný do Compositu)
  112.  
  113. Decorator - dovoľuje modifikáciu objektov počas behu
  114. - flexibilnejší než dedičnosť, pretože umôžňuje funkcionality pre subclassy ako keby dedily ale počas behu
  115. - Component (interface ktorý obsahuje základné operácie/metódy - napr. getDescription)
  116. - ConcreteComponent (základná classa, ktorá implementuje Component a ktorá sa dekoruje)
  117. - Decorator (abstract class, ktorá implementuje Component a do ktorej posiela objekt ktorý chceme dekorovať)
  118. - ConcreteDecorator (classa v ktorom sa superuje objekt ktorý jej bol poslaný do Decorator kde je uložený do premennej
  119. a v ktorej je daný objekt dekorovaný - getDescription - return pizza.getDescription() + " <>")
  120.  
  121. Facade - jednotné rozhranie, ktoré reprezentuje celý subsystém
  122. - Client/Main (vytvára Facade class a spustí metódu ktorá chceme a Facade metóda spraví všetky veci ktoré sú potrebné - Computer facade = new Computer(); -> facade.startComputer();)
  123. - Facade (obsahuje constructor v ktorom vytvárame ComplicatedClasses ktoré robia svoje vlastne operácie - Computer(){ cpu = new CPU(); hdd = ...} & startPC(){ cpu.run(); hdd.turn(); ...})
  124. - ComplicatedClasses1/2/... (classy ktoré vykonávajú svoje vlastné operácie aby sme vykonali čo chceme spraviť z Clienta/Mainu
  125.  
  126. Proxy - vytvára objekt, ktorý je reprezentáciou iného objektu aby bolo možné kontrolovať alebo pristúpiť ku dátam iného objektu
  127. - limituje prístup inej classe
  128. - ATM (bankomat) je pekný príklad využitia Proxy - limitujeme prístup ku citlivým informáciam a metódam ako zmena množstva peňazí atď.)
  129. - Client/Main (vytvárame Subject objekty do ktorých vkladáme new SubjectProxy("<data>");)
  130. - Subject (interface v ktorom sú metódy ku ktorým chcem mať prístup, aby sme nemali prístup ku všetkým dátam ConcreteSubject-u)
  131. - SubjectProxy (implementuje Subject a má vytvorený Subject ConcreteSubject premennú)
  132. - ConcreteSubject (implementuje Subject a obsahuje všetky info, keďže ide o reálne zariadenie a nie o proxy)
  133.  
  134. Bridge - oddeluje interface objektu od jeho implementácie
  135. Flyweight - používa sa keď máme príliš veľa malý objektov, ktoré sú si podobné
  136.  
  137. ////////////////////////////////////////////////////
  138.  
  139. Behavioral - riešia chovanie systému, akú objekti interaktujú. Sú založené na triedach alebo objektoch. U tried sa využíva dedičnosť a u objektov spolubráza medzi nimi a skupinami objektov.
  140.  
  141. Chain of Responsibility - dovoľuje posúvanie requestov medzi objektami v reťazi/chain-e pokiaľ to daný objekt nedokáže vyriešiť
  142. - napr. keď si žiadame isté povolenie tak po chain-of-command budeme hľadať kto nám ho môže dať
  143. - Client/Main (vytvorí Handler handler = new ConcreteHandler1(); handler.handleRequest(<data>);)
  144. - Handler (interface ktorý obsahuje handleRequest(); metódu)
  145. - ConcreteHandler1/2/... (implementujú Handler interface a handleRequest() metódu v ktorej je IF,
  146. ak dokáže spracovať tak vykonajú operáciu ak nie tak vytvoria nový handler = newConcreteHandlerX() a dajú hadler.handleRequest(<data>))
  147.  
  148. Observer - spôsob ako oznamujeme viacerým classám nejakú zmenu
  149. - observable/subject/object (uplementuje interface s add, remove a notif/update) si udržuje ArrayList s observermi, ktorým v prípade zmeny zavolá nejakú z ich metód (for-kuje (loop) a update() kazdy)
  150.  
  151. State - mení chovanie objektu keď sa zmení jeho stav
  152. - Client/Main
  153.  
  154. public class StatePatternDemo {
  155. public static void main(String[] args) {
  156. Context context = new Context();
  157.  
  158. StartState startState = new StartState();
  159. startState.doAction(context);
  160.  
  161. System.out.println(context.getState().toString());
  162.  
  163. StopState stopState = new StopState();
  164. stopState.doAction(context);
  165.  
  166. System.out.println(context.getState().toString());
  167. }
  168. }
  169.  
  170. - State (interface)
  171.  
  172. public interface State {
  173. public void doAction(Context context);
  174. }
  175.  
  176. - Context
  177.  
  178. public class Context {
  179. private State state;
  180.  
  181. public Context(){
  182. state = null;
  183. }
  184.  
  185. public void setState(State state){
  186. this.state = state;
  187. }
  188.  
  189. public State getState(){
  190. return state;
  191. }
  192. }
  193.  
  194. - ConcreteState1/2/...
  195.  
  196. public class StartState implements State {
  197.  
  198. public void doAction(Context context) {
  199. System.out.println("Player is in start state");
  200. context.setState(this);
  201. }
  202.  
  203. public String toString(){
  204. return "Start State";
  205. }
  206. }
  207.  
  208. Command - zapúdri request ako objekt (umožňuje parametrizovať daný objekt atď.) aby bol zavolaní neskôr
  209. - napr. vloženie orderov na kúpenie/predanie akcií/tovaru do listu a broker následne executne order a vykonajú sa
  210. - Client/Main (vytvára request/objekt (Stock s menom) - jablká, vytvára nové ConcreteOrders a vytvára Invoker-a, ktorému sa dané ConcreteOrders predané a on ich potom executne po jednom z listu a premaže list)
  211. - CommandBase (interface obsahujúci metódy ako execute)
  212. - ConcreteOrder1/2/... (implementuje CommandBase a ukladá si referenciu na daná objekt (Stock))
  213. - Invoker (si ukladá requesty ktoré su mu poslané do "private List<Order> list = new ArrayList<Order>();" a keď mu je povedané nech ich executne tak ich po jednom z listu vykoná a premaže)
  214.  
  215. Iterator - dovoľuje pristupovať ku špecifickému elementu(om) v skupine elementov (objektom)
  216. - Array, ArrayList, Hashtable Objects...
  217. - Client/Main
  218.  
  219. public static void main(String[] args) {
  220. ConcreteAggregate zoznam = new ConcreteAggregate();
  221. zoznam.pridajOsobu(new Osoba("Jozef"));
  222. zoznam.pridajOsobu(new Osoba("Peter"));
  223. zoznam.pridajOsobu(new Osoba("Stefan"));
  224.  
  225. Iterator iterator=zoznam.createIterator();
  226.  
  227. System.out.println(iterator.first().getMeno());
  228. System.out.println(iterator.next().getMeno());
  229. System.out.println(iterator.next().getMeno());
  230.  
  231. }
  232.  
  233. - Object/Person
  234.  
  235. public class Osoba {
  236. private String name;
  237.  
  238. public Osoba(String name,String priezvisko,int plat){
  239. this.name = name;
  240. }
  241.  
  242. public String getMeno(){
  243. return this.name;
  244. }
  245.  
  246. }
  247.  
  248. - Container/Aggregate
  249.  
  250. public interface Aggregate {
  251. public Iterator createIterator();
  252. }
  253.  
  254. - ConcreteContainer/ConreteAggregate
  255.  
  256. public class ConcreteAggregate implements Aggregate {
  257. private List<Osoba> zoznam = new ArrayList<>();
  258.  
  259. public ConcreteAggregate(){
  260.  
  261. }
  262.  
  263. @Override
  264. public Iterator createIterator() {
  265. return new ConcreteIterator(this);
  266. }
  267.  
  268. public List<Osoba> getZoznam(){
  269. return this.zoznam;
  270. }
  271.  
  272. public void pridajOsobu(Osoba osoba){
  273. zoznam.add(osoba);
  274. }
  275.  
  276. }
  277.  
  278. - Iterator
  279.  
  280. public interface Iterator {
  281. public Osoba first();
  282. public Osoba next();
  283. public Osoba currentItem();
  284. }
  285.  
  286. - ConcreteIterator
  287.  
  288. public class ConcreteIterator implements Iterator{
  289. private ConcreteAggregate aggregate;
  290. private int current = 0;
  291. public ConcreteIterator(ConcreteAggregate aggregate){
  292. this.aggregate = aggregate;
  293. }
  294.  
  295. @Override
  296. public Osoba first() {
  297. //chyba osetrenie keby bol prazdny
  298. return aggregate.getZoznam().get(0);
  299.  
  300. }
  301.  
  302. @Override
  303. public Osoba next() {
  304. //chyba osetrenie keby bol prazdny a keby nemal dalsieho
  305. return aggregate.getZoznam().get(++current);
  306. }
  307.  
  308. @Override
  309. public Osoba currentItem() {
  310. //chyba osetrenie keby bol prazdny
  311. return aggregate.getZoznam().get(current);
  312. }
  313.  
  314. }
  315.  
  316. Strategy - encapsuluje nejaký algoritmi vo vnútri classy aby sa dalo medzi nimi prepínať
  317. - Animal class má Dog a Bird classy, Animal bude implementovať Flys interface, kde budú metódy (stratégie/algos) ItFlys(), CantFly()
  318. - ked potrebuje dynamicky vyuzivat rozne chovania/behaviours pre objekty/kód
  319. - IStrategy (interface)
  320.  
  321. public interface IStrategy {
  322. public int doOperation(int num1, int num2);
  323. }
  324.  
  325. - Context
  326.  
  327. public class Context {
  328. private Strategy strategy;
  329.  
  330. public Context(Strategy strategy){
  331. this.strategy = strategy;
  332. }
  333.  
  334. public int executeStrategy(int num1, int num2){
  335. return strategy.doOperation(num1, num2);
  336. }
  337. }
  338.  
  339. - ConcreteStrategy1/2/... (OperatioAdd/Substract/Multiply) (implementuje Strategy)
  340.  
  341. public class OperationAdd/Substract/Multiply implements Strategy{
  342. @Override
  343. public int doOperation(int num1, int num2) {
  344. return num1 +/-/* num2;
  345. }
  346. }
  347.  
  348. - Client/Main
  349.  
  350. public class StrategyPatternDemo {
  351. public static void main(String[] args) {
  352. Context context = new Context(new OperationAdd());
  353. System.out.println("10 + 5 = " + context.executeStrategy(10, 5));
  354.  
  355. context = new Context(new OperationSubstract());
  356. System.out.println("10 - 5 = " + context.executeStrategy(10, 5));
  357.  
  358. context = new Context(new OperationMultiply());
  359. System.out.println("10 * 5 = " + context.executeStrategy(10, 5));
  360. }
  361. }
  362.  
  363. Visitor - definuje operáciu, ktorá sa má vykonať nad objektami bez zmeny triedy
  364. - dovoľuje pridať metódy do class (aj rôznych typov) bez zmeny týchto class
  365. - Visitor (interface)
  366.  
  367. interface Visitor {
  368. // Created to automatically use the right
  369. // code based on the Object sent
  370. // Method Overloading
  371. public double visit(Liquor liquorItem);
  372. public double visit(Tobacco tobaccoItem);
  373. public double visit(Necessity necessityItem);
  374. }
  375.  
  376. - TaxVisitor (implementuje Visitor)
  377.  
  378. class TaxVisitor implements Visitor {
  379.  
  380. // This formats the item prices to 2 decimal places
  381.  
  382. DecimalFormat df = new DecimalFormat("#.##");
  383.  
  384. // This is created so that each item is sent to the
  385. // right version of visit() which is required by the
  386. // Visitor interface and defined below
  387.  
  388. public TaxVisitor() {
  389. }
  390.  
  391. // Calculates total price based on this being taxed
  392. // as a liquor item
  393.  
  394. public double visit(Liquor liquorItem) {
  395. System.out.println("Liquor Item: Price with Tax");
  396. return Double.parseDouble(df.format((liquorItem.getPrice() * .18) + liquorItem.getPrice()));
  397. }
  398.  
  399. // Calculates total price based on this being taxed
  400. // as a tobacco item
  401.  
  402. public double visit(Tobacco tobaccoItem) {
  403. System.out.println("Tobacco Item: Price with Tax");
  404. return Double.parseDouble(df.format((tobaccoItem.getPrice() * .32) + tobaccoItem.getPrice()));
  405. }
  406.  
  407. // Calculates total price based on this being taxed
  408. // as a necessity item
  409.  
  410. public double visit(Necessity necessityItem) {
  411. System.out.println("Necessity Item: Price with Tax");
  412. return Double.parseDouble(df.format(necessityItem.getPrice()));
  413. }
  414.  
  415. }
  416.  
  417. - Visitable (interface)
  418.  
  419. interface Visitable {
  420.  
  421. // Allows the Visitor to pass the object so
  422. // the right operations occur on the right
  423. // type of object.
  424.  
  425. // accept() is passed the same visitor object
  426. // but then the method visit() is called using
  427. // the visitor object. The right version of visit()
  428. // is called because of method overloading
  429.  
  430. public double accept(Visitor visitor);
  431.  
  432. }
  433.  
  434. - Liquor/Necessity/Tobacco
  435.  
  436. class Necessity implements Visitable {
  437.  
  438. private double price;
  439.  
  440. Necessity(double item) {
  441. price = item;
  442. }
  443.  
  444. public double accept(Visitor visitor) {
  445. return visitor.visit(this);
  446. }
  447.  
  448. public double getPrice() {
  449. return price;
  450. }
  451.  
  452. }
  453.  
  454. - TaxHolidayVisitor (ConcreteVisitor class)
  455.  
  456. class TaxHolidayVisitor implements Visitor {
  457.  
  458. // This formats the item prices to 2 decimal places
  459.  
  460. DecimalFormat df = new DecimalFormat("#.##");
  461.  
  462. // This is created so that each item is sent to the
  463. // right version of visit() which is required by the
  464. // Visitor interface and defined below
  465.  
  466. public TaxHolidayVisitor() {
  467. }
  468.  
  469. // Calculates total price based on this being taxed
  470. // as a liquor item
  471.  
  472. public double visit(Liquor liquorItem) {
  473. System.out.println("Liquor Item: Price with Tax");
  474. return Double.parseDouble(df.format((liquorItem.getPrice() * .10) + liquorItem.getPrice()));
  475. }
  476.  
  477. // Calculates total price based on this being taxed
  478. // as a tobacco item
  479.  
  480. public double visit(Tobacco tobaccoItem) {
  481. System.out.println("Tobacco Item: Price with Tax");
  482. return Double.parseDouble(df.format((tobaccoItem.getPrice() * .30) + tobaccoItem.getPrice()));
  483. }
  484.  
  485. // Calculates total price based on this being taxed
  486. // as a necessity item
  487.  
  488. public double visit(Necessity necessityItem) {
  489. System.out.println("Necessity Item: Price with Tax");
  490. return Double.parseDouble(df.format(necessityItem.getPrice()));
  491. }
  492.  
  493. }
  494.  
  495. - Client/Main/VisitorTest
  496.  
  497. public class VisitorTest {
  498. public static void main(String[] args) {
  499.  
  500. TaxVisitor taxCalc = new TaxVisitor();
  501. TaxHolidayVisitor taxHolidayCalc = new TaxHolidayVisitor();
  502.  
  503. Necessity milk = new Necessity(3.47);
  504. Liquor vodka = new Liquor(11.99);
  505. Tobacco cigars = new Tobacco(19.99);
  506.  
  507. System.out.println(milk.accept(taxCalc) + "\n");
  508. System.out.println(vodka.accept(taxCalc) + "\n");
  509. System.out.println(cigars.accept(taxCalc) + "\n");
  510.  
  511. System.out.println("TAX HOLIDAY PRICES\n");
  512.  
  513. System.out.println(milk.accept(taxHolidayCalc) + "\n");
  514. System.out.println(vodka.accept(taxHolidayCalc) + "\n");
  515. System.out.println(cigars.accept(taxHolidayCalc) + "\n");
  516.  
  517. }
  518. }
  519.  
  520. Template Method - definuje kostru algoritmu tak aby potomkovia si kostru mohli upraviť a následne použiť vo forme v akej potrebujú
  521. Interpreter - includuje jazykové elementy do programu
  522. Mediator - zaisťuje komunikáciu medzi dvoma komponentami bez toho aby boli v priamej interakcií
  523. Memento - zachytí a dokáže obnoviť vnútorný stav objektu
  524.  
  525. Java theory:
  526.  
  527. Java balíky:
  528.  
  529. Java ME (Micro Edition) – mobilné telefóny a malé zariadenia
  530. Java SE (Standard Edition) – typická inštalácia Javy pre domáce počítače
  531. Java EE (Enterprise Edition) – používaná v enterprise sektore
  532. Java Card – inteligentné čipové karty (ako napr. SIM karta do mobilného telefónu)
  533. Jacarta
  534. Java 10
  535.  
  536. //zmena
  537.  
  538. Overloading - two or more methods in the same class with the same name but different arguments
  539.  
  540. void foo(int a)
  541. void foo(int a, float b)
  542.  
  543. Overriding - two methods with the same arguments, but different implementations.
  544. One of them would exist in the parent class, while another will be in the derived, or child class.
  545. The @Override annotation, while not required, can be helpful to enforce proper overriding of a method at compile time.
  546.  
  547. class Parent {
  548. void foo(double d) {
  549. // do something
  550. }
  551. }
  552.  
  553. class Child extends Parent {
  554. @Override
  555. void foo(double d){
  556. // this method is overridden.
  557. }
  558. }
  559.  
  560. Prístup ku objektom/elementom/metódam: private < package private (no modifier) < protect < public
  561.  
  562. Modifier Class Package Subclass World
  563. public Y Y Y Y
  564. protected Y Y Y N
  565. package private Y Y N N
  566. private Y N N N
  567.  
  568.  
  569. /////////////////////////
  570.  
  571. For for objects in Java:
  572.  
  573. private List<Graphic> graphicList = new ArrayList<>();
  574.  
  575. for(Graphic gr: graphicList) //foreach
  576. {
  577. gr.print();
  578. }
  579.  
  580. /////////////////////////
  581.  
  582. Encapsulation in Java is a mechanism of wrapping up the data and code together as a single unit.
  583. It also means to hide your data in order to make it safe from any modification.
  584.  
  585. We can achieve encapsulation in Java by:
  586.  
  587. Declaring the variables of a class as private.
  588. Providing public setter and getter methods to modify and view the variables values.
  589.  
  590. //////////////////////////
  591.  
  592. Polymorphism:
  593.  
  594. Overloading (static) and overriding (dynamic polymorphism) are types of polymorphism where a method is acting differently based on the situation/data/object.
  595.  
  596. //////////////////////////
  597.  
  598. Constructor - can be invoked only one time per object creation by using the "new" keyword. You cannot invoke constructor multiple times, because constructor are not designed to do so.
  599.  
  600. Method - can be invoked as many times as you want (Even never) and the compiler knows it.
  601.  
  602. //////////////////////////
  603.  
  604. KEYWORD extends is for extending a class. Preberáš všetky metódy z danej classy ale nemusíš ich použiť a môžeš ich prepísať.
  605.  
  606. KEYWORD implements is for implementing an interface. Interface obsahuje iba názvy/volania/typy metód ktoré musia byť implementované do classy ktorá ich implementuje.
  607.  
  608. A class can only extend ONE other class. A class can implement SEVERAL interfaces.
  609.  
  610. Interface: Each mobile must provide Calling and SMS facility so we can create Interface that has methods Calling, SMS, etc...
  611. So if any class Implements MobileInterface then it has to write implementation part of all method writtenMobileInterface.
  612. In our example its Calling ans SMS. Check following source code for better understanding.
  613.  
  614. IMPLEMENT
  615.  
  616. public interface MobileInterface {
  617. /* Each mobile must have calling facility */
  618. public void call();
  619. /* Each mobile must have sms facility */
  620. public void sms();
  621. }
  622.  
  623. Abstract Class: Now What other you can think of that mobile, it may have Mp3 Player, GPS, Camera, etc...
  624. but its not compulsory for mobile to have all this feature so we can create an Abstract class that has methods like Mp3Player, GPS, Camera, etc...
  625. Its not compulsory to implement all methods of SmartPhoneAbstractClass Abstract class.
  626.  
  627. EXTEND
  628.  
  629. public abstract class SmartPhoneAbstractClass {
  630.  
  631. /* Its not compulsory to have MP3 Player in each mobile */
  632. public void mp3Player(){
  633. System.out.println("Can have implementation");
  634. }
  635.  
  636. /* Its not compulsory to have GPS in each mobile */
  637. public void GPS(){
  638. System.out.println("Can have implementation");
  639. }
  640.  
  641. }
  642.  
  643. //////////////////////////
  644.  
  645. Keyword STATIC:
  646.  
  647. Static basically means that the values would be stored in the class memory.
  648. So if a class has a static variable, no matter how many instances of it you create, they all would have the same value for the variable.
  649. In other words, they all refer to the same copy. Static variables and methods can be accessed directly through the class.
  650. Though accessing them through instances wouldn't break compilation, your IDE will complain asking you to access them in a static way.
  651. Static methods can access only static variables in the class.
  652.  
  653.  
  654. “static” in Object Oriented languages means that the member is not tied to a particular instance.
  655.  
  656. A static method cannot reference the “this” object, and cannot reference any other non-static members.
  657.  
  658. A static field has only one value, which is shared across the entire application.
  659.  
  660. Static classes are interesting. In Java, a nested class that is declared static is
  661. just an ordinary class that happens to be declared inside another class.
  662. If it’s public you can instantiate it and use it just like any other class.
  663.  
  664. The interesting part is that a non-static nested class (sometimes called an “inner” class) is contained within
  665. an instance of the outer class, and can reference instance members of the containing object. Among other things, this means you
  666. cannot even create an instance of the inner class without qualifying it with an instance of the outer class.
  667.  
  668. Keyword FINAL:
  669.  
  670. Value of variables (ints, doubles etc.) cannot change.
  671.  
  672. In very simple terms it means the values once assigned cannot be modified.
  673. In the case of final variables, they should either be assigned at declaration or in the constructor. In the case of final classes, it means that they cannot be subclassed.
  674.  
  675. final int x = 5;
  676.  
  677. Reference types: For references to objects, final ensures that the reference will never change, meaning that it will always refer to the same object.
  678. It makes no guarantees whatsoever about the values inside the object being referred to staying the same.
  679.  
  680. final List<Whatever> foo;
  681.  
  682. As such, final List<Whatever> foo; ensures that foo always refers to the same list, but the contents of said list may change over time.
  683.  
  684. ////////////////////////////////////////////////////
  685.  
  686. import java.util.ArrayList;
  687. import java.util.List;
  688.  
  689. class Test {
  690. private final List foo;
  691.  
  692. public Test() {
  693. foo = new ArrayList();
  694. foo.add("foo"); // Modification-1
  695. }
  696.  
  697. public void setFoo(List foo) {
  698. //this.foo = foo; Results in compile time error.
  699. }
  700. }
  701.  
  702. //////////////////////////
  703.  
  704. private final List foo;
  705.  
  706. "foo" is an instance variable. When we create Test class object then the instance variable foo, will be copied inside the object of Test class.
  707.  
  708. If we assign foo inside a method, the compiler knows that a method can be called multiple times, which means the value will have to be changed multiple times,
  709. which is not allowed for a final variable.
  710. So the compiler decides constructor is good choice!
  711. You can assign a value to a final variable only one time.
  712.  
  713. //////////////////////////
  714.  
  715. private static final List foo = new ArrayList(); //must be static
  716.  
  717. foo is now a static variable. When we create an instance of Test class, foo will not be copied to the object because foo is static.
  718. Now foo is not an independent property of each object. This is a property of Test class.
  719. But foo can be seen by multiple objects and if every object which is created by using the new keyword which will ultimately invoke the Test constructor
  720. which changes the value at the time of multiple object creation (Remember static foo is not copied in every object, but is shared between multiple objects.)
  721.  
  722. //////////////////////////
  723.  
  724. Try, Catch, Throw, Finally:
  725.  
  726. Try: Java try block is used to enclose the code that might throw an exception. It must be used within the method. Java try block must be followed by either catch or finally block.
  727.  
  728. Catch: Java catch block is used to handle the Exception. It must be used after the try block only. You can use multiple catch block with a single try.
  729.  
  730. Finally: The finally block is executed after execution exits the try block and any associated catch clauses regardless of whether an exception was thrown or caught.
  731.  
  732. Exception: Chybová správa/classa ktorá obsahuje dané chyby a vyhodí chybu ak nastane počas behu kódu.
  733.  
  734. public static String test(){
  735. try {
  736. System.out.println("try");
  737. throw new Exception();
  738. } catch(Exception e) {
  739. System.out.println("catch");
  740. return "return";
  741. } finally {
  742. System.out.println("finally");
  743. return "return in finally";
  744. }
  745. }
  746.  
  747. //////////////////////////
  748.  
  749. Literals:
  750.  
  751. Literals in Java are a sequence of characters (digits, letters, and other characters) that represent constant values to be stored in variables.
  752.  
  753. Integer literals: 100 (base 10), 0144 (octal), 0x64 (hexa)
  754. Floating-point literals: 4.23, -0.00001
  755. Character literals: 'u0041' (capital A), \n (new line)
  756. String literals: "hello world"
  757. Boolean literals: true, false
  758. Null literal: null
  759.  
  760. //////////////////////////
  761.  
  762. JRE:
  763.  
  764. JRE is an implementation of the JVM which actually executes Java programs.
  765. It includes the JVM, core libraries and other additional components to run applications and applets written in Java.
  766. Java Runtime Environment is a must install on machine in order to execute pre compiled Java Programs.
  767. JRE is smaller than the JDK so it needs less disk space and it is so because JRE does not contain Java compiler and other software tools needed to develop Java programs.
  768.  
  769. JDK:
  770.  
  771. The Java Development Kit (JDK) is a software development environment used for developing Java applications and applets.
  772. It includes the Java Runtime Environment (JRE), an interpreter/loader (java), a compiler (javac), an archiver (jar), a documentation generator (javadoc) and other tools needed in Java development.
  773.  
  774. JVM (Java Virtual Machine):
  775.  
  776. JVM is an abstract machine. A java program execution uses a combination of compilation and interpretation.
  777. Programs written in Java are compiled into machine language, but it is a machine language for a computer that is, virtual and doesn't really exist.
  778. This so-called "virtual" computer is known as the Java virtual machine (JVM). The machine language for the Java virtual machine is called Java bytecode.
  779.  
  780. Java Virtual Machine is a program that runs pre compiled Java programs, which mean JVM executes .class files (byte-code) and produces output.
  781. The JVM is written for each platform supported by Java included in the Java Runtime Environment (JRE). The Oracle JVM is written in the C programming language.
  782.  
  783. //////////////////////////
  784.  
  785. Data types:
  786.  
  787. Primitive:
  788.  
  789. boolean - true/false
  790.  
  791. char - single 16-bit Unicode character ('\u0000' or 0 - '\uffff' 65,535)
  792.  
  793. byte - 8-bit signed integer (-128 - 127)
  794. short - 16-bit signed integer (-32768 - 32767)
  795. int - 32-bit signed integer (-2,147,483,648 - 2,147,483,647)
  796. long - 64-bit signed integer (-9,223,372,036,854,775,808 - 9,223,372,036,854,775,807)
  797.  
  798. float - single-precision 32-bit IEEE 754 floating point (used to save memory)
  799. double - double-precision 64-bit IEEE 754 floating point (generally used for decimal values)
  800.  
  801. Non-Primitive:
  802.  
  803. String:
  804.  
  805. By string literal : Java String literal is created by using double quotes.
  806.  
  807. For Example: String s = “Welcome”;
  808.  
  809. By new keyword : Java String is created by using a keyword “new”.
  810. For example: String s = new String(“Welcome”);
  811.  
  812. It creates two objects (in String pool and in heap) and one reference variable where the variable ‘s’ will refer to the object in the heap.
  813.  
  814. Array - Java Array is an object that holds a fixed number of values of a single data type.
  815. - can hold primitive, non-primitive or references
  816. - can be 2D or 3D
  817.  
  818. Reference:
  819.  
  820. A reference variable can be used to refer any object of the declared type or any compatible type.
  821.  
  822. Animal animal = new Animal("giraffe");
  823.  
  824. //////////////////////////
  825.  
  826. Enum:
  827.  
  828. An enum is a group of named constants. It can be used for defining user defined data types.
  829.  
  830. package com.ashok.enums;
  831.  
  832. enum Month {
  833. JANUARY, FEBRUARY, MARCH, APRIL, MAY, JUNE,
  834. JULY, AUGUST, SEPTEMBER, OCTOBER, NOVEMBER, DECEMBER;
  835. }
  836. public class MyEnum {
  837. public static void main(String[] args) {
  838. Month mon = Month.JANUARY;
  839. System.out.println(mon);
  840. }
  841. }
  842.  
  843. //////////////////////////
  844.  
  845. Hashtable:
  846.  
  847. Hashtable<String, Integer> numbers = new Hashtable<String, Integer>();
  848. numbers.put("one", 1);
  849. numbers.put("two", 2);
  850. numbers.put("three", 3);
  851.  
  852. Ku danej hodnote v Hastable sa pristupuje pomocou "key", čo je prvý dátovy typ (String).
  853.  
  854. //////////////////////////
  855.  
  856. Garbage Collector:
  857.  
  858. The process by which Java programs perform automatic memory management. Java programs compile to bytecode that can be run on a Java Virtual Machine, or JVM for short.
  859. When Java programs run on the JVM, objects are created on the heap, which is a portion of memory dedicated to the program.
  860. Eventually, some objects will no longer be needed. The garbage collector finds these unused objects and deletes them to free up memory.
  861.  
  862. //////////////////////////
  863.  
  864. Java Collections:
  865.  
  866. The Java collections framework (JCF) is a set of classes and interfaces that implement commonly reusable collection data structures.
  867. At times you might be required to search, sort, insert, manipulate or delete big chunks of data. You can do all that with the help of Java Collections Framework.
  868.  
  869. Collections in java is a framework that provides an architecture to store and manipulate the group of objects.
  870.  
  871. All the operations that you perform on a data such as searching, sorting, insertion, manipulation, deletion etc. can be performed by Java Collections.
  872. Java Collection simply means a single unit of objects.
  873. Java Collection framework provides many interfaces (Set, List, Queue, Deque etc.) and classes (ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet etc).
  874.  
  875. ArrayList - has dynamic length (with each added object, the lenght increases)
  876. - can't story primitive values (only objects)
  877. - can only be 1D
  878.  
  879. LinkedList - Linked List is a sequence of links which contains items. Each link contains a connection to another link. (Linkedlist object = new Linkedlist();)
  880. - Singly Linked List (reference to the next link) and Doubly Linked List (reference to the next and to the previous link)
  881.  
  882. //////////////////////////
  883.  
  884. Package:
  885.  
  886. Package is an encapsulation mechanism to group related classes and interfaces into a single module. The main purpose of packages are:
  887.  
  888. To resolve naming conflicts
  889. To provide security to the classes and interfaces. So that outside person can't access directly.
  890. It improves modularity of the application.
  891.  
  892. Class:
  893.  
  894. A template/blueprint that describes the behavior/state that the object. Class is a logical entity. Class doesn't allocated memory when it is created.
  895.  
  896. Object:
  897.  
  898. Object is an instance of a class, a physical entity. It can be created many times as required.
  899. Object allocates memory when it is created.
  900.  
  901. Nested classes:
  902.  
  903. Nested classes are divided into two categories: static and non-static.
  904. Nested classes that are declared static are simply called static nested classes.
  905. Non-static nested classes are called inner classes. (has access to outer class members/variables)
  906.  
  907. There are three reasons you might create a nested class:
  908.  
  909. organization: sometimes it seems most sensible to sort a class into the namespace of another class, especially when it won't be used in any other context
  910. access: nested classes have special access to the variables/fields of their containing classes (precisely which variables/fields depends on the kind of nested class, whether inner or static).
  911. convenience: having to create a new file for every new type is bothersome, again, especially when the type will only be used in one context
  912.  
  913. //////////////////////////
  914.  
  915. Autoboxing:
  916.  
  917. Auto Boxing is used to convert primitive data types to their wrapper class objects. Wrapper class provide a wide range of function to be performed on the primitive types.
  918.  
  919. int a = 56;
  920. Integer i = a; // Auto Boxing
  921.  
  922. Wrapper class:
  923.  
  924. Each of Java's 8 primitive type (byte,short,int,float,char,double,boolean,long) hava a seperate Wrapper class Associated with them.
  925. These Wrapper class have predefined methods for preforming useful operations on primitive data types.
  926.  
  927. String s = "45";
  928. int a = Integer.parseInt(s); // sets the value of a to 45.
  929.  
  930. Unboxing:
  931.  
  932. Unboxing is opposite of Auto Boxing where we convert the wrapper class object back to its primitive type.
  933. This is done automatically by JVM so that we can use a the wrapper classes for certain operation and then convert them back to primitive types as primitives result int faster processing.
  934.  
  935. Integer s = 45;
  936. int a = s; auto UnBoxing;
  937.  
  938. In case of Collections which work with objects only auto unboxing is used.
  939.  
  940. ArrayList<Integer> al = new ArrayList<Integer>();
  941. al.add(45);
  942.  
  943. int a = al.get(0); // returns the object of Integer. Automatically Unboxed.
  944.  
  945. //////////////////////////
  946.  
  947. Java Spring:
  948.  
  949. In short, Spring framework helps you build web applications.
  950. It takes care of dependency injection, handles transactions, implements an MVC framework and provides foundation for the other Spring frameworks (including Spring Boot)
  951.  
  952. MVC stands for Model View Controller.
  953. Developers use an MVC architecture for the same reason web designers use HTML (the model) and CSS (the view) instead of mixing structure, data,
  954. and layout together — the separation of presentation and data reduces complexity and allows developers to — for instance — build new front-end interfaces without having to change the core logic.
  955.  
  956. //////////////////////////
  957.  
  958. *method* *parameter*
  959. public setWeight(int newWeight){
  960.  
  961. }
  962. *argument*
  963. x.setWeight(80);
  964.  
  965. //////////////////////////
  966.  
  967. public static void main(String args[])
  968.  
  969. public - It means that you can call this method from outside of the class you are currently in.
  970. This is necessary because this method is being called by the Java runtime system which is not located in your current class.
  971.  
  972. static - When the JVM makes call to the main method there is no object existing for the class being called therefore it has to have static method to allow invocation from class.
  973.  
  974. void - Java is platform independent language and if it will return some value then the value may mean different things to different platforms.
  975. Also there are other ways to exit the program on a multithreaded system. Detailed explaination.
  976.  
  977. main - It's just the name of method. This name is fixed and as it's called by the JVM as entry point for an application.
  978.  
  979. String[] args - These are the arguments of type String that your Java application accepts when you run it.
  980.  
  981.  
  982. //////////////////////////
  983.  
  984. File streams:
  985.  
  986. I/O Streams: These are sequences of bytes that you can read from (InputStream and its subclasses) or write to (OutputStream and its subclasses).
  987.  
  988. Java 8 streams: Basically a generalization of lists: they are sequences of objects; the difference is in how you use them.
  989.  
  990. //////////////////////////
  991.  
  992. Java JDBC:
  993.  
  994. Java JDBC je Java API (Application Programming Interface) ktoré slúži na pripojenie a interakciu Java kódov s relačnými databázami (SQL, MySQL, PostgreSQL...). JABC používa JDBC motorist na rozhovor s databázami.
  995. JDBC (Java Database Connectivity)-to-ODBC (Open Database Connectivity) dovoľuje premostiť komunikáciu do akéhokoľvek ODBC zdroju dát vo Java Virtual Machin (JVM).
  996.  
  997. Java JPA/Hibernate & ORM:
  998.  
  999. ORM - Object-Relational Mapping
  1000. JPA - Java Persistence Api
  1001. Hibernate - ORM Framework that uses JPA
  1002.  
  1003. JPA vyuziva ORM, ze si pouzijes presne Hibernate alebo eclipselink alebo openJPA a ti namapuje sql objekty na java objekty
  1004. ale je zalozene na JDBC
  1005.  
  1006. Java FX/JFX:
  1007.  
  1008. A GUI toolkit for Java/Java Framework, bundled as part of the regular JVM and JDK. It replaces Swing (predchodca).
  1009. It utilizes a XML architecture to map UI elements to the code.
  1010.  
  1011. Databases:
  1012.  
  1013. SQL - Structured Query Language
  1014. DBMS - Database management system (data are stored as files)
  1015. RDBMS - Relational database management system (data are stored as tables)
  1016.  
  1017. PL/SQL - procedurálne rozšírenie Oracle SQL databázového systému. Umožňuje písať imperatívny kód, ktorý je vykonávaný systémom riadenia bázy dát (SRDB).
  1018.  
  1019. Oracle SQL, MySQL, PostgreSQL - najznámenšie databázové systémy líšiace sa syntaxov, featurami atď. (Oracle SQL je platené)
  1020.  
  1021. Primary key - v jednej tabuľke, slúži na indexovanie dát v tabuľke (môže byť iba jeden, nemôže byť NULL)
  1022. Foreiging key - hodnota v tabuľke ktorá je primárnym kľúčom v inej tabuľke (môže ich byť viacero v tabuľke, môže byť NULL)
  1023.  
  1024. Relationships:
  1025.  
  1026. One-to-One (1:1) - každý riadok v jednej tabulke je linknutý ku presne jednúmu riadku v druhej tabuľke
  1027. One-to-Many (1:m) - jedna tabulka s primarnym klucom a v druhej cudzi kluc na primarny z prvej tabulke
  1028. Many-to-Many (m:n) - tu sa používa spojovacia tabuľka (obe tabuľky sú ku spojovacej tabuľke vo vzťahu 1:m)
  1029.  
  1030. // creates a database
  1031. CREATE DATABASE db1;
  1032.  
  1033. // drops the database
  1034. DROP DATABASE db1;
  1035.  
  1036. // sets default database for queries
  1037. USE db1;
  1038.  
  1039. // creates a table
  1040. CREATE TABLE Account
  1041. (
  1042. ID INT NOT NULL,
  1043. Name VARCHAR2(16) NOT NULL,
  1044. Password VARCHAR2(32) NOT NULL,
  1045. Email VARCHAR2(32) NOT NULL,
  1046. Account_Created DATE NOT NULL,
  1047. PRIMARY KEY (ID)
  1048. );
  1049.  
  1050. // alters the table
  1051. ALTER TABLE Account
  1052. ADD <column_name> <datatype (INT)>;
  1053.  
  1054. // drops the table
  1055. DROP TABLE db1;
  1056.  
  1057. // shows info about a table
  1058. DESCRIBE <table>;
  1059.  
  1060. // creates a select
  1061. SELECT ID, Name, Email, TRUNC(Subscription_Ends) - TRUNC(sysdate) as Days_Remaining
  1062. FROM ACCOUNT
  1063. WHERE (TRUNC(Subscripti on_Ends) - TRUNC(sysdate)) <= 14;
  1064.  
  1065. // inserts data into the table
  1066. INSERT INTO Profession (ID, Name)
  1067. VALUES (1, 'Alchemist');
  1068.  
  1069. // inserts data into the table without specifying order of collumns
  1070. INSERT INTO person SET first_name = 'John', last_name = 'Doe';
  1071.  
  1072. // updates specific data in the table at given position
  1073. UPDATE table_name SET column1 = value1, column2 = value2 WHERE id=100;
  1074.  
  1075. // deletes data from table where...
  1076. DELETE FROM Customers
  1077. WHERE CustomerName='Alfreds Futterkiste';
  1078.  
  1079. // replaces string/values on specific place (works exactly like INSERT only deletes the old value and inserts the new one even if they are exactly the same)
  1080. REPLACE INTO t1 VALUES (...)
  1081.  
  1082. // truncates the table
  1083. TRUNCATE TABLE table_name;
  1084.  
  1085. // rollbacks all changes
  1086. ROLLBACK;
  1087.  
  1088. // comits all changes
  1089. COMMIT;
  1090.  
  1091. // creates a view
  1092. CREATE VIEW avg_values_races AS SELECT Race, TRUNC(AVG(HP)) as Average_HP, TRUNC(AVG(MP)) as Average_MP, TRUNC(AVG("EXP")) as Average_EXP
  1093. FROM CHARACTER
  1094. GROUP BY Race
  1095. ORDER BY Race
  1096. WITH READ ONLY;
  1097.  
  1098. // lists the number of customers in each country, sorted high to low:
  1099. SELECT COUNT(CustomerID), Country
  1100. FROM Customers
  1101. GROUP BY Country
  1102. ORDER BY COUNT(CustomerID) DESC;
  1103.  
  1104. // inner join - selects records that have matching values in both tables.
  1105. SELECT Orders.OrderID, Customers.CustomerName
  1106. FROM Orders
  1107. INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID;
  1108.  
  1109. // natural join - selects data from both tables (they have to have same name for collumns, same data type and you can't use ON clause on natural join)
  1110. SELECT *
  1111. FROM table1
  1112. NATURAL JOIN table2;
  1113.  
  1114. // intersect - vráti riadky ktoré sú v oboch tabuľkách (musia byť rovnakého typu a mena)
  1115. SELECT Name, BirthDate FROM Employee
  1116. INTERSECT
  1117. SELECT Name, BirthDate FROM Customer
  1118.  
  1119. // IN - dovoľuje špecifikovať viacero WHERE
  1120. SELECT * FROM Customers
  1121. WHERE Country IN ('Germany', 'France', 'UK');
  1122.  
  1123. // EXISTS - The EXISTS operator is used to test for the existence of any record in a subquery and returns true if the subquery returns one or more records.
  1124. SELECT SupplierName
  1125. FROM Suppliers
  1126. WHERE EXISTS (SELECT ProductName FROM Products WHERE SupplierId = Suppliers.supplierId AND Price < 20);
  1127.  
  1128. GROUP BY - zgrupuje výsledok selectu s rovnakými atributmi v danom stĺpci
  1129. ORDER BY - zoradí dáta podľa daného stĺpca
  1130. INNER JOIN - selects records that have matching values in both tables
  1131. NATURAL JOIN - selects data from both tables (they have to have same name for collumns, same data type and you can't use ON clause on natural join)
  1132. (FULL) OUTER JOIN - elect vráti dáta ktoré matchujú v oboch tabuľkách a všetky dáta z oboch tabuliek
  1133. LEFT/RIGHT JOIN - select vráti dáta ktoré matchujú v oboch tabuľkách a všetky dáta z ľavej/pravej tabuľky
  1134. INTERSECT - vráti riadky ktoré sú v oboch tabuľkách (musia byť rovnakého typu a mena)
  1135. IN - dovoľuje špecifikovať viacero WHERE
  1136. EXISTS - operator is used to test for the existence of any record in a subquery and returns true if the subquery returns one or more records.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement