|  | 
|  | 1 | +import java.io.Closeable; | 
|  | 2 | +import java.io.IOException; | 
|  | 3 | + | 
|  | 4 | +/** | 
|  | 5 | + * Every class that implements those two interfaces can be closed automatically in a try with resource block. | 
|  | 6 | + * | 
|  | 7 | + * Closeable vs AutoCloesable | 
|  | 8 | + * @link{https://stackoverflow.com/questions/13141302/implements-closeable-or-implements-autocloseable} | 
|  | 9 | + * Closeable extends AutoCloseable. | 
|  | 10 | + * Closeable close() method throws IOException. | 
|  | 11 | + * AutoCloseable close() method throws Exception. | 
|  | 12 | + * | 
|  | 13 | + * Inner static class can access outer class static field without the need of referencing the outer class. | 
|  | 14 | + * | 
|  | 15 | + **/ | 
|  | 16 | +public class Challenge_3 { | 
|  | 17 | + | 
|  | 18 | + static String marvelHero = ""; | 
|  | 19 | + | 
|  | 20 | + public static void main( String[] args ) throws IOException { | 
|  | 21 | + Logan logan = new Logan(); | 
|  | 22 | + //firstly, the new PeterParker() instruction is executed | 
|  | 23 | + new Challenge_3().executeAction(new PeterParker(), logan); | 
|  | 24 | + System.out.println(marvelHero + logan.wolverineCloseCount); | 
|  | 25 | + } | 
|  | 26 | + | 
|  | 27 | + private void executeAction( Closeable spiderMan, AutoCloseable wolverine ) throws IOException { | 
|  | 28 | + /** | 
|  | 29 | + * As We can see after the code execution of the try block we close the resources automatically | 
|  | 30 | + * and we jump to the catch block only if some exception has been thrown. | 
|  | 31 | + */ | 
|  | 32 | + try (spiderMan;wolverine){ | 
|  | 33 | + wolverine.close(); | 
|  | 34 | + }catch (Exception e){ | 
|  | 35 | + marvelHero+= "?"; | 
|  | 36 | + spiderMan.close(); | 
|  | 37 | + } | 
|  | 38 | + } | 
|  | 39 | + static class Logan implements AutoCloseable{ | 
|  | 40 | + public static int wolverineCloseCount=0; | 
|  | 41 | + | 
|  | 42 | + @Override | 
|  | 43 | + public void close() throws IOException { | 
|  | 44 | + marvelHero +=">"; | 
|  | 45 | + wolverineCloseCount++; | 
|  | 46 | + if (wolverineCloseCount >= 1) throw new IOException(); | 
|  | 47 | + } | 
|  | 48 | + } | 
|  | 49 | + static class PeterParker implements Closeable{ | 
|  | 50 | + @Override | 
|  | 51 | + public void close() throws IOException { | 
|  | 52 | + marvelHero += "#"; | 
|  | 53 | + } | 
|  | 54 | + } | 
|  | 55 | +} | 
0 commit comments