OCA Java SE 8 Programmer I Master Cheat Sheet

Transcription

SKILLCERTPROOCA Java SE 8 Programmer I MasterCheat Sheet1. Java Class StructureCode style in the exam Don't expect best practices Really bad code there The International Obfuscated C Code Contest: http://www.ioccc.org/o http://www.ioccc.org/2015/dogon/prog.c#define So long#define R rand()#include math.h #include X11/Xlib.h #define T(i,F) ((So long)(i) F)#define O(c,L,i) c*sin(i) L*cos(i)#define y(n,L) for(n 0; n L 3; n )#define P(v,L) d 0; y(l,)d T(L*l[v],l*20);#define X(q) q 10&63 q 24&4032 q 38&258048char J[1 18]; int G[W*p], ,k,I W/4 1,w p/4 1; float C,B,e;unsigned So long A,n,d, t,h,x, f,o,r,a,l,L,F,i,s,H 1 18,b 250,D[1 14],z[W*p],q 0x820008202625a0;main(){Display *j XOpenDisplay(0);Window u 0);XImage *Y W,p,32,0); XEvent M; for(XMapWindow(j,u); XSelectInput( j,u,1)&&a65307; ){ if(!H){ if(XCheckWindowEvent(j,u,1,&M)){ a XLookupKeysym(&M.xkey,0);*(a&1?&C:&B)- (.05-a/2% 2*.1)*!(a1& 4092 3920);a 2&0xfe0 0xfc0 (s a 2&31); }else{ y(k,p ){ F k%w* 4 k/w;float a[6],S (F-p/2.) /p;y( ,W ){i %I*4 /I; if(F p&i W){ o 1; L i F*W;if(l i&3);else{ l F&3; o W; } h z[L-o*l]; f z[L (4l)*o]; t F-p/2 i-W/2; r h f; if(!l !t (int)r (!(h- 3&3)&&258063&r 38)){ float V (i-W/2.)/p,U O(S,1,B),m 32768,Q m; a[4] O(-1,S,B); a[3] O(U,V,C); a[5] O(-V,U,C); P((a 3),s*42); t (A d);f 0;y(n,){floatN a[n 3], E 1024/fabs(N); b N 0;float K (((q 20*n) -b) !b&1023)/1024.; y(d,)a[d] a[d 3]pg. 1

SKILLCERTPRO*E; a[n] round(a[n]); P(a,K); i q d; P(a,1); e E*K; for(;e m; i d){ l X(i); t r l (l l-(1 6*n))&63 6*n; if(b){ r l; l t; } if(J[r])l r; if(t J[l]){x (n-1)?(i i 40)&1023 i 8&4190208 4194304:i&1023 i 28&4190208 (b l r) 23; if(h D[(x 6&0xf x 14&0x3f0) t*768]){ o h; f n l*4 x 32; m e; } if(t 8&e Q)Q e; } e E; } }b (255-((f&3) 2)%3*51)*(1-m/32768); o o*b 8; G[L] o 32 8 o&16711935; z[L] 3*(Q m) f b 56; } else{d l*(f 8 40) (4-l)*(h 8 40) 2&16774143; o D[(d 6&15 d 14&1008) J[(int)h/4]*768]*(b h 56) 8; G[L] o 32 8 o&16711935; z[L] (int) h d 32 b 56; } }}} q A;XPutImage(j, u 0,DefaultGC(j,J[X(q)] 0),Y,0,0,0,0,W,p); }}else{ L --H/768;J[H] R%16*(R%4 abs((H 6&63)-32) abs((H 12&63)-32)-3);i H &15;F H %768 4; if(L 16){if(L-1 !(R%3))b R%96 255; l i*i*3 i*81/4&3; a L 3?L-8?L-5?9858122:12365733-488848*((i F/4*4)%8&&F%4):R%2*5298487:3352537*L*L-14202379*L 19205553; if(L 4)if(F l 18)a 6990400;elseif(l F-19)b* 0.7; if(L 3){ if((i-1&15) 14&(F-1&15) 14&!(F&16)){ a 12359778; 7-i; k 7-F%16; 31; k k 31; b 196-R%32 (k ?k: )%3*42;} else{ b* 1 R%2*(.5-(i&1)); } } D[H] (a&16711935 (a&65280) 24)*(b (F 5)) 8&0xff00ff00ff; } } }}Classes vs. Objects Class: building blocks. Template to create objects Objects: runtime instances of classes State: all objects of all our classesClass members Fields: class-level variables Methods: functions, procedures Method signature:access modifier return typepg. 2methodName(parameter type parameter name, .)

SKILLCERTPROValid classpublic class Person {}.class House {Person owner;int rooms;void cleanRoom(int roomNumber) {}}Java building blocks Classes Interfaces Enums (OCP) Spot errorspublic class Main {public static void main(String[] args) {new House().rooms();}}class House {String ownerName;int rooms;void cleanRoom(int roomNumber) {roomNumber rooms;}int Rooms;int rooms() {}} Missing return statementEasier with an IDE & compiler, right? :-Dpg. 3

SKILLCERTPROComments// one line Comments/*Multiline comment*//** Fancy Multiline comment**//**** Java Doc comment (NOT IN THE EXAM)*/ Spot errors// hello // world/* // hello world *//*/*// Hello// World*/*/Rules .java source files one public class in every file, at most if there's one public class - file name same as class as much non-public classes as we want Spot errors// Wolf.javapg. 4

SKILLCERTPROclass Wolf {}class wolf {} Spot errors// House.javapublic class House {}class Person {}class Monkey {}Main method Entry point to our program Java Runtime injects parameterspublic static void main(String[] args) {}Main method IIAll validpublic static void main(String[] main) {// write your code here}public static void main(String. main) {// write your code here}pg. 5

SKILLCERTPROpublic static void main(String m[]) {// write your code here} Watch outpublic void main(String m[]) {// write your code hereSystem.out.println("Hello");}Error: el método principal no es static en la clase Main,defina el método principal del siguiente modo:public static void main(String[] args) Spot errorspublic class Main {public static void main(String args) {new House().rooms();}}class House {String ownerName;int rooms;void cleanRoom(int roomNumber) {roomNumber rooms;}int Rooms;int rooms() { return rooms; }} Spot errorspublic class Main {public static void main(String args) { // array of Strings!new House().rooms();}}class House {String ownerName;int rooms;void cleanRoom(int roomNumber) {pg. 6

SKILLCERTPROroomNumber rooms;}int Rooms;int rooms() { return rooms; }}Exercise: print all parameters from command line if its a number?JRE vs JDK JRE: to run Java programs JDK: to compile Java programs JDK contains a JRE in order to run (test) programso inside the JDK folder there's a JRE with java commando javac & other tools, only in JDKCompiling from command line javac -version java Main Compile & run classes by hand. Read page 14Imports PIC: Package, Imports, Classesimport java.lang.*; by default import one class or all classes in that package (wildcard) non recursive package name: lowercase legal identifiers separated by . pg. 7

SKILLCERTPRO Watch outRedundantimport java.lang.Exception;import java.lang.*;Errorimport java.lang.;Packages as namespaces avoid conflicts with two classes, same name FQCN: Fully Qualified Class Name default package no package Watch outError!import java.sql.Date;import java.util.Date;// try with *public class Main {public static void main(String m[]) {Date d;}}Exercise create our own packages, compile from command linelaunch from command line java package.ClassWithMainMethodConstructorspg. 8

SKILLCERTPRO methods to initialize objects after creation creation in three phases Stack (references), Heap (Objects, References) Watch outpublic class A {String a "Wow";public A() {a "much A's";}public void A() {}public static void main(String m[]) {A a new A();}}Using object fields (get & set values)public class A {String a "Wow";String s a " much String!";// reading fieldpublic static void main(String m[]) {A a new A();a.a "Hello";// setting fieldSystem.out.println(a.a);// reading field}}Instance initializer blockspublic class Doge {String meme "Wow!";{meme "Much instance initializer blocks ";pg. 9

SKILLCERTPRO}public Doge() {meme " so exciting";}public static void main(String[] args) {Doge d new Doge();System.out.println(d.meme);}{meme " very confusing!";}}Instance initializer blocks[fit] WATInstance initializer blockspg. 10

SKILLCERTPRO only for people who doesn't know to chain constructors to make code confusing to build objects without using constructorsJava Reserved wordsabstract ault edpublicreturnshortstrictfp superswitchsynchronized enuminstanceofpackagestaticMisterios Transient: no se serializa esa propiedad (y así no se graba a disco / envia porla red) Volatile: puede ser accedida por múltiples hilos: está sincronizada Strictfp: compatibilidad operaciones floating point 1 Goto: reservado 2Tipos primitivos vs. Clases Wrapperboolean Boolean byte Byte char Character double Double float Float int Integer longLong short ShortIdentificadores Legales: los que compilan Convenciones de código de Sun Estándares de nombrado de JavaBeanspg. 11

SKILLCERTPROConvenciones de nombres Sun Clases: 1ª mayúscula CamelCase Interfaces: 1ª mayúscula CamelCase atributos: 1ª minúscula CamelCase métodos: 1ª minúscula CamelCase constantes: CONST NAMEJavaBeans naming standars JavaBean:o constructor público sin argumentosopropiedades privadasoget / set / is (boolean)opublic void setProp(PropTipo val)opublic PropTipo getProp();oListeners: add / remove ListenerIdentificadores: reglas empiezan por letra [A-Za-z], , NO empiezan por número desp. del 1er. carácter, cualquier combinac de letras, números y , case sensitive no se pueden usar las palabras clave de JavaIdentificadores (test)int ;int 10;int 1niesta;pg. 12

SKILLCERTPROintintintintint:hola;hola:;otro identificador ;e te e ta mal;pero-Este-Bien;Reference types reference: pointer references: variables en la pila, apuntan a objetos en el heap Stack: ovariables localesoparámetrosHeap:ovariables de instancia (iVars)oobjetosString name null;Declarando variables declarar variables tipos simpleso no podemos usar null con tipos simples declarar variables referenciasDeclarando variablesint i null;String s1, s2, s3;s1 new String("Hello");s2 "World!";MiClase c new MiClase();pg. 13

SKILLCERTPRO instancia un nuevo objeto en el montón lo inicializa lo liga a la referencia c (que es una var. local, luego está en la pila)Variable initialization (rules) local vars fields oiVars: se establecen a un valor por defectooprimitivosoreferencias a objetosoarraysclass variablesBlocks of code & variable scope class method if, while, switch, .int i 10;{int i 11;int j 10;// error: redefining var// only visible inside block}alcance de variables static iVars local / automatic blockpg. 14

SKILLCERTPROOrder of elements PIC: Package, Imports, Classes methods, fields: everywhereDestroying objects Garbage collectorfinalize()o notjconsoleguaranteed to be calledBenefits of Java OO Encapsulation Platform independent Robust Simple SecureOperators and statementsNumeric promotion int long long int float float byte, short, char -- promote to int alwayspg. 15

SKILLCERTPROByte woesbyte b1 1;byte b2 1 b1;// error--byte b1 1;byte b2 (byte)(1 b1);Byte woesbyte b3 b1 ;b1 b1 1;b1 b1 1;System.out.println(b1 1);// OK// OK// OK// error \ (ツ) / Assignment no es int i 10;long l 10;double d 10.9;float f 10.0;Binary arithmetic operatorsUnary operators , -, , -- postfix & prefix instanceof no entra en el examenpg. 16

SKILLCERTPROLogical operators , &, !: int / boolean , &&: short-circuit operatorsTernary operator ?if-then-else curly braces not mandatoryint x 0;if (x 10) {x 11;} else {x 10;}// value of x?if-then-elseint x 0;if (x 10)x 11;x--;elsex 10;switchint x 0;switch (x) {case 10:case 7:case 4:break;pg. 17

SKILLCERTPROdefault:}switchString name "spongebob";switch (name) {case "spongebob":case "7":case "PatrickStar":break;default:}Dates and Times in Java 8Current DateLocalDate now LocalDate.now();System.out.println(now);// 2015-11-08 LocalDate: only date (not time)can't do new LocalDate();import java.time.LocalDate;Date with year, month, dayLocalDate firstOfJanuary2015 LocalDate.of(2015, Month.JANUARY, e inmutable!LocalDate 12Oct1492 LocalDate.of(1492, Month.OCTOBER, 12);pg. 18

SKILLCERTPRO12Oct1492 .plusDays(800);System.out.println( 12Oct1492 );// 1492-10-12LocalDate other 12Oct1492 .plusDays(800);System.out.println(other);// 1494-12-21LocalTimeLocalTime timeNow LocalTime.now();System.out.println(timeNow);// 13:51:53.382 LocalTime: sólo tiempoLocalDateTime: fecha y horaLocalTime inmutable!LocalTime timeNow w.plusHours(1);System.out.println(timeNow);// 19:57:24.995// 19:57:24.995 plusMinutes / minusMinutes plusSeconds / minusRecorrer intervalosLocalDate start LocalDate.of(2015, Month.APRIL, 10);LocalDate end LocalDate.of(2015, Month.APRIL, 20);while (start.isBefore(end)) {System.out.println(start);start 015-04-132015-04-14pg. 19

182015-04-19TimeZones [ // console output20:05:25.17011:05:25.17219:05:25.173[ 1]: no entra en el examen re-the-java-timezone-ids/Period// Create task every weekPeriod everyWeek Period.ofWeeks(1);start LocalDate.now();end LocalDate.of(2016, Month.APRIL, 10);while (start.isBefore(end)) {System.out.println(start);start start.plus(everyWeek);}Parse datesDateTimeFormatter formatter e date LocalDate.parse("2010/10/40", formatter);System.out.println(date); pg. 20can throw java.time.format.DateTimeParseException (Runtime)

SKILLCERTPROCore Java APIsString concatenation1. both operands numeric, means addition2. either operand a STring, means concatenationi.operands gets promoted into String3. expression evaluated from left -- rightString concatenationString s1 1 3 "j";String s2 "1" 3.0;String s3 1 2.5 " ";// "4j"// 13.0// 3.5 String s4 1 "" 1;String s5 1 2 3;String s6 null 1;// ?// ?// ?Strings are inmutable inmutable: can't change once created final: can't be made mutable by inheritanceString s "Hello";s "goodbye";// original "Hello" object releasedCreating my own inmutable classesfinal class Person {private String name;Person(String name) {this.name name;}public String getName() {pg. 21

SKILLCERTPROreturn name;}}// after that code.Person diego new Person("Diego");diego.getName();// setName() doesn't existsCreating my own inmutable classes// v2, with "setter"final class Person {private String name;Person(String name) {this.name name;}public String getName() {return name;}public Person setName(String name) {return new Person(name);}}Inmutable for what? Parsing JSON / XML objects just read from the net Using global settings in my app I don't want to change In general, avoiding mutable state Is A Good ThingWatch out!String s "hello";String s1 s.concat(" Mary Lou");s.concat(" goodbye s);pg. 22

SKILLCERTPROStrings & the String poolString s "Hello";String s1 new("Hello");Memory testSystem.out.println("start");try {Thread.sleep(3000);} catch (InterruptedException e) {e.printStackTrace();}// 3 sec delaySystem.out.println("lets go!");List String list new ArrayList (100000);for (int i 0; i 1000000; i ) {String s "number";// change for String s new String("number");list.add(s);}try {Thread.sleep(10000);} catch (InterruptedException e) {e.printStackTrace();}// 10 sec delayjvisualvm Comes for free with JDK in your JAVA HOME http://visualvm.java.net/download.htmlpg. 23

SKILLCERTPROString methods length charAt indexOf substring toLowerCase / toUpperCase equals / equalsIgnoreCase startsWith / endsWith contains replace trimStringBuilder mutable String good for concat Strings good for the GC / memory fragmentationpg. 24

SKILLCERTPROStringBuilder s new StringBuilder("Apple Google ln(s.charAt(3));s.append(" Yahoo!");System.out.println(s);Typical SQL statementString query "Select ( " id ", " name " ) from " table " where " id " " theId; at least 10 String objects. now 1000 customers connect to this page. 10000 objects in memory.StringBuilder vs StringBuffer StringBuffer: old, Thread safe StringBuilder: shiny, shiny, new, not Thread safe, use thisEquality ( vs equals) Sirve para ver la igualdad lógica entre dos objetos Object.equals compara referencias (es idéntico a ) Podemos sobreescribirlo Sin equals no podemos usar estos objetos como Key en HashTable @Overridepublic boolean equals(Object obj) {// OJO: se recibe un Objectif (obj instanceof Person2 && ((Person2)obj).getName().equals(getName())) {return true;}return false; }pg. 25

SKILLCERTPROEquals contract reflexivo: x.equals(x) debe devolver true simétrico: x.equals(y) --- y.equals(x) transitivo: x.equals(y) -- true, y.equals(z) -- true x.equals(z) -- true consistente: si x.equals(y) devuelve true y no cambiamos nada, múltiplesinvocaciones devuelven siempre lo mismo x.equals(null) -- false (con x no null)equals - hashcode contract Si dos objectos se consideran iguales mediante equals, deben devolver elmismo hash code value Invocaciones sucesivas sobre un mismo objeto que no cambiamos debendevolver el mismo valor NO es obligatorio que si dos objetos no son iguales (equals) deban devolverhash codes distintos: pueden devolver siempre el mismoArrays definition / instantiation// goodint[] a1 new int[10];int a2[] new int[10];Integer ai[] new Integer[10];// badintintintintinta3[10]a4[] a5[10]a6[] a6[] pg. 26 new int[10];new int[]; new int[];new int[]();new int(10);memory (when using reference types)

SKILLCERTPROArrays: sorting / searching SortingInteger ai[] {4, 1, 3};Arrays.sort(ai);for (int i: ai) {System.out.println(i);}Arrays: sorting watch outString ai[] {"4", "11", "03", "1", "100"};Arrays.sort(ai);for (String i: ai) {System.out.println(i);}// output:031100114Arrays: search can only search a sorted arrayint ai[] {1, 7, 24, 32};Arrays.sort(ai);System.out.println(" * " Arrays.binarySearch(ai, 11));System.out.println(" * " Arrays.binarySearch(ai, 24));Varargs java(seen in chap 4)pg. 27

SKILLCERTPROMultidimensional arraysArrayList import java.util.* creating an ArrayLIst add() remove() set() isEmpty(), size() clear() contains() equals(): same elements in the same orderWrapper classes to convert values between types to have collections of simple valuesMethods / encapsulationMethod signaturepublicfinalthrows RuntimeExceptionaccess finalException listmodifier (optional)pg. 28void return type name sayHello(String message) method name parameter list throws

SKILLCERTPRO return type: check type method name: valid identifierReturn typeVoid m1(String s) {return null;}void m1(String s) {// no return}String m1() {return "hello";}Varargs vargars must be lastargument there can be only one1. Exercise: create a method calcMedian that returns the median value ofn int numbers. At least you must pass one value2. Exercise: create a method hodor that given some Strings returns a single stringwith s1 " Hodor! " s2 " Hodor! "Access modifiers for members 3 keywords, 4 levels: private, protected, (package), publicAccess modifiers: explain why are all wrongpublic void public m1() {}public void m1 {pg. 29

SKILLCERTPRO}package void m1(String s) {}protected int m1(String s) {}protected void final m1(String s) {}protected void m1(String s);Method modifiers static: class method abstract: method has no body, child class should override it final: can't override this method synchronized: thread safe strictfp (not in OCA/OCP): floating point calculations IEEE 754 [ 1] native (not in OCA/OCP): to interact with native libraries (C, C )[ 1]: Strictfp ensures that you get exactly the same results from your floating pointcalculations on every platform. If you don't use strictfp, the JVM implementation isfree to use extra precision where ic variables methods static importsPassing by value pg. 30passing by value vs. passing by refo in Java there's only pass by value

SKILLCERTPROowe pass a copy of the reference simple types object typesOverloading methodsLambdas use IntelliJ to learn how to write them :-D A Lambda is just a piece of code we can pass around. Think of it as a functionpointer. Lambda that takes a string as param and doesn't return anything(String s) - { .statements; };Without lambdas.Runnable task1 new Runnable() {@Overridepublic void run() ith Lambdas.Runnable task2 () - { System.out.println("Yeah!"); };task2.run();We can omit {} if there's only one statementRunnable task2 () - System.out.println("Yeah!");task2.run();pg. 31

SKILLCERTPROFunctional interface a functional interface has exactly one abstract method default methods in an interface have an implementation, they are not abstractpublic class Main {public static void main(String[] args) {Downloadable d;d uri - { return uri " Downloaded"; };}}interface Downloadable {String download(String uri);}Pass something to the lambda, return somethinginterface Eater {public String eat(int i);}Eater e (int i) - { return "Eaten i " i; };System.out.println(e.eat(11));Functional programming focus on what, not in who "I want to convert all elements in this array to String", instead of "loopthrough." Lambda expressiono block of codepg. 32oyou can store it in a variableoyou can pass it aroundomethods without a name

SKILLCERTPROLambda expressionsStream Person f people.stream().filter((Person p) - {return p.isHappy() true;});f.forEach(p - System.out.println(p.getName()));Classic First class functions: map Not in OCA, but usefulList String names Arrays.asList("Grouch", "Chicc", "Harp");// forEach to printnames.stream().forEach(e - System.out.println(e ));names.stream().map((e) - e "o").forEach(e - System.out.printf(e "\n"));names.stream().map((e) - e.toUpperCase()).forEach(e - System.out.printf(e "\n"));Predicates functional interface Predicatehas a test methodboolean test(T t);Predicate String p s - o"));System.out.println(p.test("Groucho"));// -- false// -- truePredicates can be composed!Predicate String startsWithG s - s.startsWith("G");Predicate String correctSize s - s.length() 7;Predicate String correctName ctName.test("Groucho"));pg. 33// -- true

SKILLCERTPROPredicates for filtering streamsList String names Arrays.asList("Grouch", "Chicc", "Harp");Predicate String p s - (System.out::println);OptionalsOptional String s names.stream().reduce((s1, s2) - { return s1 s2; });if (s.isPresent()) {System.out.println(s.get());}Fun with functionsInterface Function T,R - T: the type of the input to the function- R: the type of the result of the function// m1() takes a String and returns a String, hence the String, String static Function String, String m1() {return new Function String, String () {@Overridepublic String apply(String s) {return s.concat(" and two boiled eggs!");}};}Fun with functionsstatic Function String, String m2() {return new Function String, String () {@Overridepublic String apply(String s) {return s.concat(" yeah!");}};}// .pg. 34

SKILLCERTPROFunction String, String f;f m1();System.out.println(f.apply("Hola"));f m2();System.out.println(f.apply("Hola"));Class DesignInheritance IS A vs HAS A single inheritance extends vs implements a class can t extend an Interface can't implement a Class against inheritance: rocedural.htmlAccess modifiers for top-level classes public, (default) not private nor protected!o we can have inner or nested classes with those modifiers (not in OCA)// not in the same file: each class in a differente .java file// also: name the filespublic class A {} yay or nay?private class B {}pg. 35

SKILLCERTPRO yay or nay?public default class B {} yay or nay?Calling super members only public & protectedConstructors default constructor: added by the compiler calling always super() or this() constructor chaining watch out! private constructorsConstructors: private constructors!class A {private A() {}}class B extends A { // comp error: There's no default constructor available in A// we can't call super()!}Constructors: private constructors!// problem solvedclass A {private A() {}public A(String s) {pg. 36

SKILLCERTPRO}}class B extends A {public B() {super(null);}}Init orderpublic class Main {public static void main(String[] args) {System.out.println("In main");Test t1 new Test();Test t2 new Test();}}class Test {static int staticNumber 1;static {System.out.println("static block 1 " staticNumber);staticNumber 10;}{System.out.println("instance block 1");}public Test() {System.out.println("Inside constructor");}{System.out.println("instance block 2");}static {System.out.println("static block 2 " staticNumber);}}In mainstatic block 1static block 2instance blockinstance blockpg. 3711012

SKILLCERTPROInside constructorinstance block 1instance block 2Inside constructorsuper() vs superclass A {private int i1;int i2;}class B extends A {public B() {System.out.println(i2);i2 10; // OK, can see itSystem.out.println(i2);super.i2 11; // it's the sameSystem.out.println(i2);this.i2 12; // same againSystem.out.println(i2);}}Overloading vs. Overriding override a method: same method in child class overload a method: same method name, different parametersOverriding checks same signature method in child class at least as accessible as method in parent class can't throw new / broader checked exceptions if returns a value, same type or sibclass of the method in parent class(covariant returns) [ 1][ 1]: preserves the ordering of typespg. 38

SKILLCERTPROfinal methods can't be overriddenRedeclaring private methods private methods can't be overriddenStatic method hiding no such thing as static method overridding existsclass A {public static void m1() {System.out.println("In A");}}class B extends A {public static void m1() {// not "overridding", just same nameSystem.out.println("In B");}}A.m1(); // In AB.m1(); // In BA a new B();((B)a).m1(); // In BHiding instance variables that's why getters/setters are nice!class A {private int i1;int i2;}class B extends A {pg. 39

SKILLCERTPROint i1; // no problem, doesn't exist hereString i2; // hiding instance vars!public B() {System.out.println(i2);i2 "b"; // OK, String varSystem.out.println(i2);super.i2 11; // OK, int varSystem.out.println(super.i2);this.i2 "b2"; // sOK, String varSystem.out.println(i2);}}Abstract classes a class that is marked as abstract can't instantiate objects from this class can have concrete & abstract methods exercise: create an abstract class excersise: extend an abstract classInterfaces method signature inside interfaces: public abstract always marker interface: empty interface variables inside interfaces: public static final always (static constants)Interface inheritance can inherit from multiple interfacesinterface I {void m1();}interface II extends I {pg. 40

SKILLCERTPROvoid m1();public abstract void m2();}class A implements II {@Overridepublic void m1() {}@Overridepublic void m2() {}}Default methods in interfacespublic interface Test {public default int getInt() {return 1;}} can't be abstract, final, static problems with multiple inheritance?Static methods in interfacesinterface I {void m1();static void sm1() {System.out.println("sm1");}}Polymorphism we can "see" only the part of the object we're interested in at runtime, if we call a method, the true one is the method from the instanceclas, not the reference onepg. 41

SKILLCERTPROExceptionsAn "Exceptional" familyObject class Throwable -- class Error -- class Exception - class RuntimeExceptionTypes of exceptions all Exceptions are created & injected by the Runtime checked "Compile-time" exceptionso handle-or-declare rule non-checked runtime exceptionsShould I "catch" Errors? never, ever never really don't do it ever I'm serious don'tTry-catch-finallytry {// do something that can throwpg. 42

SKILLCERTPRO} catch (Exception e) {// do something if this exception is injected} finally {// do this always}Try-catch gotchasError! Needs a blocktryint i 0;catch (Exception e) ;This is finetry {int i 0;} catch (Exception e) { }Try-catch gotchasJust one try, pleasetry {} try {} catch (Exception e) {}Try-catch gotchas// we can have a try-catch with Throwabletry {int i 0;} catch (Throwable t) {// Pokémon catch: Gotta catch'em all!}try {int i 0;} catch (Exception t) {// i ;pg. 43Error: i - local to try block

SKILLCERTPRO}Try-catch gotchas// can have more than one catchtry {int i 0;} catch (Exception e) {} catch (Throwable t) {}try {int i 0;} catch (Throwable t) {} catch (Exception e) { // error: Exception has already been caught}Creating your own exceptions// Runtime, non-checked Exceptionclass NonCheckedException extends RuntimeException {}// Compile-time, checked exception, handle or declare ruleclass CheckedException extends Exception {}Catch-Or-Declare rule (Checked exceptions)public class Main {public static void main(String[] args) {throwsNonChecked(); // no problem with non-checkedtry {throwsChecked();} catch (CheckedException e) {e.printStackTrace();}}static void throwsNonChecked() {pg. 44

SKILLCERTPROthrow new NonCheckedException();}static void throwsChecked() throws CheckedException {throw new CheckedException();}}What does this prints? import java.io.IOException;public class Main {public static void main(String[] args) {try {System.out.println("DogeBegin");new Main().saveToDisk();} catch (IOException e) {System.out.println(e.getMessage());} finally {System.out.println("DogeFinally");}}void saveToDisk() throws IOException{throw new IOException("Such litte space. Much files. Wow");}}What does this prints?DogeBeginSuch litte space. Much files. WowDogeFinallyWhat does this prints? import java.io.IOException;public class Main {public static void main(String[] args) {try {System.out.println("DogeBegin");new Main().saveToDisk();} catch (IOException e) {System.out.println("IODoge" e.getMessage());pg. 45

SKILLCERTPRO} catch (Exception e) {System.out.println("ExceptionDoge" e.getMessage());} finally {System.out.println("DogeFin

OCA Java SE 8 Programmer I Master C